MegaHydronicsM
Convex Community15mo ago
2 replies
MegaHydronics

Accessing database in an action

I'm hoping to better understand why
ActionCtx
does not expose
db
. This forces me to write much longer code like the first below, instead of the second.
export const set = internalAction({
  args: { key: v.string() },
  handler: async (ctx, { key }) => {
    const exists = await ctx.runQuery(internal.db.user._exists, { key })
    if (exists) return

    const response = await fetch(...)
    const args = await response.json()
    ctx.runMutation(internal.db.user._insert, args)
  },
})

export const _insert = internalMutation({
  args: v.object(userSchema),
  handler: async (ctx, args) => {
    await ctx.db.insert('user', args)
  },
})

export const _exists = internalQuery({
  args: { key: v.string() },
  handler: async (ctx, { key }) => {
    const user = await ctx.db.query('user').withIndex('key', q => q.eq('key', key)).unique()
    return user !== null
  },
})


export const set = internalAction({
  args: { key: v.string() },
  handler: async (ctx, { key }) => {
    const user = await ctx.db.query('user').withIndex('key', q => q.eq('key', key)).unique()
    if (user !== null) return

    const response = await fetch(...)
    const args = await response.json()
    await ctx.db.insert('user', args)
  },
})
Was this page helpful?