next.jsprismatrpc

TRPC Multiple Inputs


I have a TRPC public procedure in my NextJS project. Currently one of the methods, I pass in the shopping cart of a customer, which is an array of objects. I want to add the user details in addition to the array of objects for the cart. I can't find any documentation online about multiple TRPC inputs, and I can't use useContext on the TRPC backend. Could someone assist please?


 createCheckoutSession: publicProcedure.input(
        cartSchema).
        query(async (opts) => {
            const cart = opts.input;
            // const user = useGetUserData();
            // console.log(user);

         

        }),


export const cartSchema = z.array(
    z.object({
        productId: z.string(),
        name: z.string(),
        categoryId: z.string(),
        price: z.number(),

        cartQuantity: z.number(),
        live: z.boolean(),
        inCart: z.number(),
        description: z.string(),
        imageUrl: z.array(z.string()),
    }));

I want to add the below, which is also stored in context



export const UserSchema = z.object({
    userId: z.string(),
    sessionId: z.string(),
    firstName: z.string(),
    surname: z.string(),
});


Solution

  • In general if you want multiple inputs, you can put them in an object

    createCheckoutSession: publicProcedure.input(
        z.object({
            cart: cartSchema,
            user: userSchema,
        })
    ).query(async (opts) => {
        const cart = opts.input.cart;
        const user = opts.input.user;
        // do stuff with them
    }),
    

    That being said for the specific case you're mentioning, the frontend should almost never have authoritative information about the user. That's the backend's job.