oscklmO
Convex Community2y ago
5 replies
oscklm

Help migrating to use withUser() from convex-helpers and questions regarding the library

Hello, so i recently started migrating over to use some of the nice helpers etc. that convex-helpers brings.

I started with trying to refactor the way i handle auth and getting my user object, and ran into some minor issues, that raised some questions when using withUser() and useQuery() in a react component.

Here are some code for context, and easier understanding. Questions are listed below the code snippets

// withUser.ts
import { customCtx } from 'convex-helpers/server/customFunctions'
import { zCustomMutation, zCustomQuery } from 'convex-helpers/server/zod'

import { QueryCtx, mutation, query } from '../_generated/server'

export async function getUserByTokenIdentifier<Ctx extends QueryCtx>(ctx: Ctx) {
  const identity = await ctx.auth.getUserIdentity()
  if (!identity) {
    throw new Error('Unauthenticated call to function requiring authentication')
  }
  const user = await ctx.db
    .query('user')
    .withIndex('by_token', (q) => q.eq('tokenIdentifier', identity.tokenIdentifier))
    .unique()
  if (!user) throw new Error('User not found')
  return user
}

const addUser = customCtx(async (ctx: QueryCtx) => ({
  user: await getUserByTokenIdentifier(ctx),
}))

export const mutationWithUser = zCustomMutation(mutation, addUser)

export const queryWithUser = zCustomQuery(query, addUser)
Was this page helpful?