JavascriptMickJ
tRPC3y 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...

Is there a way to implement this with multiple input parsers (https://trpc.io/docs/procedures#multiple-input-parsers) ?? what would that look like?
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
Was this page helpful?