Michael HolmesM
Convex Community3y ago
2 replies
Michael Holmes

Is this the way to include / join a table?

I'm extending Doc<"organizationCourses"> into an interface OrganizationCourse that includes course.
import { query } from '../_generated/server';
import { v } from 'convex/values';
import { OrganizationCourse } from '../interfaces';
import { paginationOptsValidator } from 'convex/server';

export const getOrganizationCourses = query({
  args: { id: v.id('organizations'), paginationOpts: paginationOptsValidator },
  handler: async (ctx, args) => {
    try {
      let organization = (await ctx.db.get(args.id)) as Organization;

      if (!organization) throw new Error('Organization not found');

      const organizationCourses = await ctx.db
        .query('organizationCourses')
        .withIndex('organization_course_index', q => q.eq('organizationId', organization!._id))
        .order('desc')
        .paginate(args.paginationOpts);

      // Include each course
      const coursesPromises = organizationCourses.page.map(orgCourse =>
        ctx.db.get(orgCourse.courseId)
      );
      const courses = await Promise.all(coursesPromises);

      organizationCourses.page.forEach((orgCourse: OrganizationCourse, index) => {
        orgCourse.course = courses[index];
      });

      return { data: organizationCourses, error: null };
    } catch (error) {
      console.error('organizationCourses error', error);
      return { data: null, error: 'There was a problem' };
    }
  },
});
Was this page helpful?