tRPCttRPC
Powered by
JavascriptMickJ
tRPC•3y ago•
14 replies
JavascriptMick

Best way to implement input based validation on a router procedure

Hi guys, bit of a noob. I have already created a 'protectedProcedure', ensuring the user is logged in, but for some of my procedures, I also want to ensure the user is an ADMIN for the account specified on the input. This is my first try with validation just added at the top of the procedure implementation...
  changeUserAccessWithinAccount: protectedProcedure
    .input(z.object({ user_id: z.number(), account_id: z.number(), access: z.enum([ACCOUNT_ACCESS.ADMIN, ACCOUNT_ACCESS.OWNER, ACCOUNT_ACCESS.READ_ONLY, ACCOUNT_ACCESS.READ_WRITE]) }))
    .query(async ({ ctx, input }) => {
      // validate that the context user is an admin within the account specified as an input param.... where should this go.. an additional input parser?
      const test_membership = ctx.dbUser.memberships.find(membership => membership.account_id == input.account_id);
      if(!test_membership || (test_membership?.access !== ACCOUNT_ACCESS.ADMIN && test_membership?.access !== ACCOUNT_ACCESS.OWNER)) {
        throw new TRPCError({ code: 'UNAUTHORIZED' });
      }
      //....do the thing...
  changeUserAccessWithinAccount: protectedProcedure
    .input(z.object({ user_id: z.number(), account_id: z.number(), access: z.enum([ACCOUNT_ACCESS.ADMIN, ACCOUNT_ACCESS.OWNER, ACCOUNT_ACCESS.READ_ONLY, ACCOUNT_ACCESS.READ_WRITE]) }))
    .query(async ({ ctx, input }) => {
      // validate that the context user is an admin within the account specified as an input param.... where should this go.. an additional input parser?
      const test_membership = ctx.dbUser.memberships.find(membership => membership.account_id == input.account_id);
      if(!test_membership || (test_membership?.access !== ACCOUNT_ACCESS.ADMIN && test_membership?.access !== ACCOUNT_ACCESS.OWNER)) {
        throw new TRPCError({ code: 'UNAUTHORIZED' });
      }
      //....do the thing...

Is there a way to implement this with multiple input parsers (https://trpc.io/docs/procedures#multiple-input-parsers) ?? what would that look like?
Define Procedures | tRPC
Procedures in tRPC are very flexible primitives to create backend functions; they use a builder pattern which means you can create reusable base procedures for different parts of your backend application.
Define Procedures | tRPC
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

How do you call a router procedure from another router procedure?
chicoCchico / ❓-help
2y ago
procedure input context
MugetsuMMugetsu / ❓-help
4y ago
Best way to wrap procedure for error handling
danecandoDdanecando / ❓-help
10mo ago
Procedure with generic input?
hagabakaHhagabaka / ❓-help
3y ago