allen
allen11mo ago

Repository Design Pattern

I'm playing with a repository design pattern for Convex database models, and wanted to get some feedback from the community. What this solves for me: ☑️ Shared common DB methods to keep code DRY and centralized. ☑️ DB field default setting on inserts. ☑️ Reduces passing context variable around to helper functions (done once on instantiation of the repo). I may look into injecting repositories into the request context with something like handler: withRepos( async(ctx, args) => { ctx.repos.users(...) }) similar to how withUser works, so they are pre instantiated and ready to consume. Here is a gist with an overview of my approach. Would appreciate your input on concept and direction. https://gist.github.com/allenhartwig/a015aaccc7dfb9ea25285c36513c13ca
Gist
Convex Repository Design Pattern
Convex Repository Design Pattern. GitHub Gist: instantly share code, notes, and snippets.
2 Replies
allen
allenOP11mo ago
(cc @ian )
ian
ian11mo ago
I just posted a comment there how I'd use the new customFunction helpers to inject them into ctx. I called it ctx.models.users . Copied here: convex/functions.ts
import { query as rawQuery } from '@/convex/_generated/server';
import { customQuery } from 'convex-helpers/server/customFunctions';

export const query = customQuery(rawQuery, customCtx((ctx) => ({ models: { users: new UserQueryRepo(ctx) } }));
import { query as rawQuery } from '@/convex/_generated/server';
import { customQuery } from 'convex-helpers/server/customFunctions';

export const query = customQuery(rawQuery, customCtx((ctx) => ({ models: { users: new UserQueryRepo(ctx) } }));
usersWithFavoriteColor.ts
import { query } from '@/convex/functions';
export default query({
args: {
favoriteColor,
},
async handler(ctx, args) {
return ctx.models.users.getAllByFavoriteColor(args.favoriteColor);
}
});
import { query } from '@/convex/functions';
export default query({
args: {
favoriteColor,
},
async handler(ctx, args) {
return ctx.models.users.getAllByFavoriteColor(args.favoriteColor);
}
});

Did you find this page helpful?