pwuexecP
Convex Community14mo ago
3 replies
pwuexec

Type inference is not ok. Is assuming the user properties are null

import { query } from "./_generated/server";
import { paginationOptsValidator } from "convex/server";
import { getAll } from "convex-helpers/server/relationships";

export const list = query({
  args: { paginationOpts: paginationOptsValidator },
  handler: async (ctx, { paginationOpts }) => {
    // Fetch a page of tutors
    const results = await ctx.db.query("tutors").paginate(paginationOpts);

    // Extract user IDs from the tutors
    const userIds = results.page.map((t) => t.user);

    // Fetch all user documents corresponding to the user IDs
    const users = await getAll(ctx.db, userIds); // Everything here is not null

    // Combine tutor and user information
    const page = await Promise.all(
      results.page.map(async (tutor) => {
        const user = users.find((u) => u._id === tutor.user); // THIS IS NOT NULLABLE...

        // Generate the URL for the user's profile image
        const imageUrl = await ctx.storage.getUrl(user!.image);

        return {
          ...tutor,
          user: {
            ...user,
            image: imageUrl,
          },
        };
      })
    );

    return {
      ...results,
      page,
    };
  },
});
Was this page helpful?