t3dotgg / chirp

https://xn--uo8h.t3.gg/
389 stars 60 forks source link

Question: using superjson in createTRPCContext causing error leads to failed prisma operations #33

Closed itsanishjain closed 1 year ago

itsanishjain commented 1 year ago
import { initTRPC, TRPCError } from "@trpc/server";
import { type CreateNextContextOptions } from "@trpc/server/adapters/next";
import { prisma } from "@/lib/prisma";

export const createTRPCContext = (opts: CreateNextContextOptions) => {
  return {
    prisma,
  };
};

/**
 * 2. INITIALIZATION
 *
 * This is where the tRPC API is initialized, connecting the context and transformer.
 */
import superjson from "superjson";
import { ZodError } from "zod";

const t = initTRPC.context<typeof createTRPCContext>().create({
  transformer: superjson,
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.cause instanceof ZodError ? error.cause.flatten() : null,
      },
    };
  },
});

/**
 * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
 *
 * These are the pieces you use to build your tRPC API. You should import these a lot in the
 * "/src/server/api/routers" directory.
 */

/**
 * This is how you create new routers and sub-routers in your tRPC API.
 *
 * @see https://trpc.io/docs/router
 */
export const createTRPCRouter = t.router;

/**
 * Public (unauthenticated) procedure
 *
 * This is the base piece you use to build new queries and mutations on your tRPC API. It does not
 * guarantee that a user querying is authorized, but you can still access user session data if they
 * are logged in.
 */
export const publicProcedure = t.procedure;

Getting this error

[
    {
        "error": {
            "json": {
                "message": "[\n  {\n    \"code\": \"invalid_type\",\n    \"expected\": \"object\",\n    \"received\": \"undefined\",\n    \"path\": [],\n    \"message\": \"Required\"\n  }\n]",
                "code": -32600,
                "data": {
                    "code": "BAD_REQUEST",
                    "httpStatus": 400,
                    "stack": "",
                    "path": "createUser",
                    "zodError": {
                        "formErrors": [
                            "Required"
                        ],
                        "fieldErrors": {}
                    }
                }
            }
        }
    }
]

I am adding tRpc to my existing app so didn't use create-t3 Any idea why?

Tested if I remove transformer: superjson, prisma works also tested using the same zod and superjson version as this repo, but no success

itsanishjain commented 1 year ago

My Bad I didn't add the data transformer for context

https://trpc.io/docs/server/data-transformers