T
tRPC

Validating input inside middleware declaration

Validating input inside middleware declaration

Bblitzjb2/10/2023
const enforceUserIsCreatorOfEvent = t.middleware(({ ctx, next, input }) => {
if (!input.eventId || !ctx.session?.user) {
throw new TRPCError({ code: "BAD_REQUEST" });
}

const { eventId } = input;
const { user } = ctx.session;

if (!user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}

const event = await ctx.prisma.event.findUnique({
where: {
id: eventId,
},
});

if (!event) {
throw new TRPCError({ code: "NOT_FOUND" });
}

if (event.creatorId !== user.id) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}

return next();
}
const enforceUserIsCreatorOfEvent = t.middleware(({ ctx, next, input }) => {
if (!input.eventId || !ctx.session?.user) {
throw new TRPCError({ code: "BAD_REQUEST" });
}

const { eventId } = input;
const { user } = ctx.session;

if (!user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}

const event = await ctx.prisma.event.findUnique({
where: {
id: eventId,
},
});

if (!event) {
throw new TRPCError({ code: "NOT_FOUND" });
}

if (event.creatorId !== user.id) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}

return next();
}
But type of input is unknown and gives rise to a bunch of type errors Apologies in advance for the newbie question
AKAlex / KATT 🐱2/10/2023
You need to add an input validator before https://trpc.io/docs/procedures#multiple-input-parsers I'd only recommend doing this through a middleware if it is actually reused in multiple procedures

Looking for more? Join the community!

T
tRPC

Validating input inside middleware declaration

Join Server