MugetsuM
tRPC3y ago
5 replies
Mugetsu

Can I force metadata with the createCaller?

I have custom metadata which I check within the middleware. Im trying to write tests for this. Currently no single procedure is using the meta and I wonder If I can test this somehow. Can I add meta on the fly to the procedure with createCaller??

const t = initTRPC
  .context<typeof createTRPCContext>()
  .meta<MetaOptions>()
  .create({
    transformer: superjson,
    errorFormatter({ shape, ctx }) {
      const { data, ...rest } = shape

      return {
        ...rest,
        data: {
          ...data,
          traceId: ctx?.req?.traceId,
          schemaId: ctx?.req?.schemaId,
        },
      }
    },
    defaultMeta: { allowedRoles: [] },
  })


const enforceUserRoles = enforceUserIsAuthed.unstable_pipe(
  ({ ctx, meta, next }) => {
    const currentRoles = ctx.req?.authorisation?.userSecurityGroups ?? []
    const allowedRoles = meta?.allowedRoles ?? []

    if (
      allowedRoles.length &&
      !allowedRoles.some((role) => currentRoles.includes(role))
    ) {
      throw new TRPCError({
        code: 'FORBIDDEN',
        message: 'User role not allowed',
      })
    }

    return next({ ctx })
  },
)
Was this page helpful?