#Example on how to use customAction
4 messages · Page 1 of 1 (latest)
Let me check the knowledge base for you. One moment! :books:
Sure, here are a couple of examples of using customAction in Convex:
- Example from a Discord support thread:
export const authAction = customAction(
action,
customCtx(async (ctx) => {
const userId = (await ctx.auth.getUserIdentity())?.subject;
if (!userId) {
throw new ConvexError("must be logged in");
}
const user: any = await ctx.runQuery(internal.users.getUserById, {
userId,
});
if (!user) {
throw new ConvexError("user not found");
}
const _id: Id<"users"> = user._id;
const isPremium: boolean = user.isPremium;
})
);
In this example, customAction is used to create an action that checks if a user is logged in and if the user exists. If either check fails, it throws an error. Otherwise, it retrieves the user's ID and premium status. Source (https://discord.com/channels/1019350475847499849/1202973619970375710)
- Example from the Convex Stack documentation:
export const actionWithSession = customAction(action, {
args: SessionIdArg,
input: async (ctx, { sessionId }) => {
const { runSessionQuery, runSessionMutation, runSessionAction } =
runSessionFunctions(ctx, sessionId);
return {
ctx: {
...ctx,
runSessionQuery,
runSessionMutation,
runSessionAction,
},
args: { sessionId }, // Note: you can also pass it through as an arg.
};
},
});
In this example, customAction is used to define an action that injects the session ID into the context, so you don't have to pass it manually. It uses runSessionFunctions to define functions like ctx.runQuery but with the session ID injected. Source (https://stack.convex.dev/track-sessions-without-cookies#3-for-actions-userunsessionfunctions)