Blitz
Blitz16mo ago

Validating input inside middleware declaration

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
3 Replies
Alex / KATT 🐱
Alex / KATT 🐱16mo ago
You need to add an input validator before
Alex / KATT 🐱
Alex / KATT 🐱16mo ago
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.
Alex / KATT 🐱
Alex / KATT 🐱16mo ago
I'd only recommend doing this through a middleware if it is actually reused in multiple procedures