amppA
Convex Community15mo ago
13 replies
ampp

Looping over tables with normalizeId?

I've looked all over at posted examples of normalizeId and all related posts and i can't figure out if there is any other way to get a proper runtime tableName that isn't saved in the db.

Is there any real downside to this, no performance hit right? When looping through say 10 tables for the one that might have the id.

I'd like to be clear what all the options are. I know ents doesn't have ctx.db.get(id) but i havent seen that done either.

Working code:
export const testString = sessionQuery({
  args: { id: v.id('dataPool') },
  handler: async (ctx, args) => {
    const dataPool = await ctx.table('dataPool').get(args.id)

    const test = await queryIdString(ctx, dataPool.idUnionFieldOrString as string)

    return test
  },
})

async function queryIdString(ctx: SessionQueryCtx, idString: string) {
  const tableNames = ['users', 'members', 'events']

  const tableResults = await Promise.all(
    tableNames.map(async (tableName) => {
      const test = ctx.table(tableName as any).normalizeId(idString)
      return test ? { tableName, test } : null
    })
  )
  const result = tableResults.filter((result) => result !== null)

  if (result.length === 0) {
    return null
  }

  return ctx.table(result[0].tableName as any).get(result[0].test)
}
Was this page helpful?