aadishA
Convex Community3mo ago
14 replies
aadish

Using Neverthrow with functions

error image attached.
example backend code:
import type { QueryCtx, MutationCtx } from '../_generated/server';
import type { Doc } from '../_generated/dataModel';
import { ResultAsync } from 'neverthrow';
import { query, mutation } from '../_generated/server';
import { v } from 'convex/values';
import { err, ok } from 'neverthrow';

export function requireUser(ctx: Ctx): ResultAsync<Doc<"users">, string> {
    return ResultAsync.fromPromise(
      (async () => {
        const identity = await ctx.auth.getUserIdentity();
        if (!identity) throw new Error();
        const user = await ctx.db
          .query('users')
          .withIndex('byTokenIdentifier', (q) => q.eq('tokenIdentifier', identity.subject))
          .first();
        if (!user) throw new Error();
        return user;
      })(),
      () => "unauthenticated"
    );
}


export const listNames = query({
  handler: async (ctx) => {
    return await requireUser(ctx)
      .map(async (user) => {
        const pages = await ctx.db
          .query('campaigns')
          .withIndex('byUserId', (q) => q.eq('userId', user._id))
          .order('desc')
          .collect();
        return pages.map((c) => ({ id: c._id, name: c.name }));
      })
  },
});

I imagine its just because Convex can't serialize the Neverthrow Result/Ok object to JSON, is there a clean workaround to this?
image.png
Was this page helpful?