Mugetsu
Mugetsu2y ago

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 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 })
},
)
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 })
},
)
4 Replies
Nick
Nick2y ago
If you're testing the middleware, why not create a procedure just for the test? Then you can write whatever metadata you want
Mugetsu
MugetsuOP2y ago
But I would create that procedure like a normal one (something like empty procedure?) or inside the test itself?
Nick
Nick2y ago
However you like, you just need your t instance with your types on and you can create a router for testing
Mugetsu
MugetsuOP2y ago
Could you give me an example how that would look like. Im bit confused Ok nwm I got it ! Thank you