Felipe Olaya Ospina
Felipe Olaya Ospina

Reputation: 103

Unable to find Prisma Client in GraphQL context. Please provide it under the `context[\"customPrisma\"]` key

This is the error

"message": "Unable to find Prisma Client in GraphQL context. Please provide it under the context["customPrisma"] key"

stacktrace

stacktrace": [
            "Error: Unable to find Prisma Client in GraphQL context. Please provide it under the `context[\"customPrisma\"]` key.",
            "    at getPrismaFromContext (webpack-internal:///(api)/./prisma/generated/type-graphql/helpers.js:25:15)",
            "    at FacturaCrudResolver.createOneFactura (webpack-internal:///(api)/./prisma/generated/type-graphql/resolvers/crud/Factura/FacturaCrudResolver.js:42:51)",
            "    at C:\\Users\\felip\\OneDrive\\Documentos\\evergreen-fin\\evergreen-facturacion\\node_modules\\type-graphql\\dist\\resolvers\\create.js:31:98",
            "    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"
          ]
        }
      }
    }

I'm working with Graphql and Apollo server to test a mutation that i need to send some data to the DB. the GQL server API in nextJS is the next one:

import 'reflect-metadata';
import 'ts-tiny-invariant'
import { NextApiRequest, NextApiResponse } from 'next';
import { PrismaClient } from '@prisma/client';
import { ApolloServer } from 'apollo-server-micro';
import Cors from 'micro-cors'
import { resolvers } from '../../prisma/generated/type-graphql';
import { buildSchema } from 'type-graphql';
//import prisma from '../../config/prisma' 
const prisma = new PrismaClient();

const cors = Cors({
    allowMethods: ['POST', 'GET', 'OPTIONS', 'HEAD']
})

interface Context {
    p: PrismaClient;

}

export const config = {
    api:{
        bodyParser: false,
    },
}


const serverGraphql = async (req: NextApiRequest, res: NextApiResponse) => {
    const schema = await buildSchema({
        resolvers: resolvers,
        validate: false
    })
    const server = new ApolloServer({
        schema: schema,
        introspection: true,
        context: (): Context => ({ p: prisma })
    });
    const start = server.start()
    await start;
    return server.createHandler({
        path: '/api/graphql'
    })(req, res)
}


export default cors((req:any, res:any) => {
    if (req.method === "OPTIONS") {
        res.end()
        return false;
    }
    return serverGraphql(req,res);
})

In the documentation of Type-graphql i see tha i need to add the context to the generator of the .prisma file where i put the models for migrate the DB

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"

}



generator typegraphql {
  provider           = "typegraphql-prisma"
  output             = "../prisma/generated/type-graphql"
  contextPrismaKey = "customPrisma" -> THERE IS THE CUSTOMPRISMA WHERE I SEE THE ERROR IN Apollo server 
  emitTranspiledCode = true
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id       Int       @id @default(autoincrement())
  email    String    @unique
  nombre   String?
  role     Role      @default(CLIENT)
  facturas Factura[]
  profile  Profile?
}

model Profile {
  id     Int    @id @default(autoincrement())
  bio    String
  user   User   @relation(fields: [userId], references: [id])
  userId Int    @unique
}

model Factura {
  id         Int      @id @default(autoincrement())
  createdAt  DateTime @default(now())
  moneda     String   @db.VarChar(3)
  monto      Float
  pais       String
  esEfectivo String?  @default("efectivo")
  published  Boolean  @default(true)
  cliente    User     @relation(fields: [clienteId], references: [id])
  clienteId  Int
}

enum Role {
  CLIENT
  ADMIN
}

The Mutation is the next one enter image description here

Upvotes: 1

Views: 705

Answers (1)

In the prisma schema, change contextPrismaKey to p instead of customPrisma

Upvotes: 1

Related Questions