David Alonso
David Alonso6mo ago

Best way to call an `authenticatedQuery` from another `authenticatedQuery`

I've defined a customQuery as follows:
export const authenticatedQuery = customQuery(
queryRaw, // The base function we're extending
{
args: {
// This type makes sure we can't just forget to pass the clerkOrgId
clerkOrgId: v.string(),
userTokenIdentifier: v.optional(v.string()),
},
input: async (ctx, args) => {
const { user, workspace } = await enhanceClientAuthContext(
ctx,
args.clerkOrgId,
args.userTokenIdentifier
);
// Authorization checks should be done on the specific query function based on the info added to the context

return { ctx: { user, workspace }, args: { ...args } };
},
}
);
export const authenticatedQuery = customQuery(
queryRaw, // The base function we're extending
{
args: {
// This type makes sure we can't just forget to pass the clerkOrgId
clerkOrgId: v.string(),
userTokenIdentifier: v.optional(v.string()),
},
input: async (ctx, args) => {
const { user, workspace } = await enhanceClientAuthContext(
ctx,
args.clerkOrgId,
args.userTokenIdentifier
);
// Authorization checks should be done on the specific query function based on the info added to the context

return { ctx: { user, workspace }, args: { ...args } };
},
}
);
This works great in cases when I call this query from the client, but if I want to call this query from another authenticatedQuery it feels a bit clunky and double work is required to create the custom context, when ideally it could just be passed around. Looking for advice on the cleanest way to do this 🙏
3 Replies
Michal Srb
Michal Srb6mo ago
Declare
import { CustomCtx } from "convex-helpers/server/customFunctions";
export type AuthenticatedQueryCtx = CustomCtx<typeof authenticatedQuery>;
import { CustomCtx } from "convex-helpers/server/customFunctions";
export type AuthenticatedQueryCtx = CustomCtx<typeof authenticatedQuery>;
and pass the custom ctx around. Queries don't allow calling other queries directly (relevant docs: https://docs.convex.dev/functions/query-functions#splitting-up-query-code-via-helpers)
Queries | Convex Developer Hub
Queries are the bread and butter of your backend API. They fetch data from the
David Alonso
David AlonsoOP6mo ago
Thanks! I guess this would be the recommended approach for calling an authenticatedMutation from an authenticatedQuery as well? and viceversa too?
Michal Srb
Michal Srb6mo ago
You can declare helpers that are used from queries and mutations, yeah. (helpers that write to the db cannot be used from queries)

Did you find this page helpful?