dannyeloD
Convex Community16mo ago
5 replies
dannyelo

Optimizing Function Calls by Avoiding Redundant Abstractions

The problem I’m facing is that I’m using an extra layer of abstraction in my code that doesn’t seem necessary. I have a function called getCurrentUserInternal, which is basically just a wrapper around another function called getCurrentUser. I’m using this wrapper to access user information inside another function, getFacturapiLiveInstance.

The problem is that getCurrentUser accepts QueryCtx, and in the action I only have access to ActionCtx.
Is there a better way?

convex/users.ts
export const getCurrentUser = async (ctx: QueryCtx) => {
  const identity = await ctx.auth.getUserIdentity()
  if (!identity) {
    throw new Error('Called getCurrentUser without authentication present')
  }

  const user = await ctx.db
    .query('users')
    .withIndex('by_token', (q) =>
      q.eq('tokenIdentifier', identity.tokenIdentifier),
    )
    .unique()

  if (!user) {
    throw new Error('User not found')
  }

  return user
}

export const getCurrentUserInternal = internalQuery({
  args: {},
  handler: async (ctx) => {
    return await getCurrentUser(ctx)
  },
})


convex/facturapi_usenode.ts
'use node'

// ...imports

export const getFacturapiLiveInstance = async ({
  organizationId,
  ctx,
}: {
  organizationId: Id<'organizations'>
  ctx: ActionCtx
}): Promise<Facturapi> => {
  await ctx.runQuery(internal.users.getCurrentUserInternal)
  await getCurrentUser(ctx) -> // this ctx is an ActionCtx

  // rest of the code...
}
Was this page helpful?