question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

prisma repeats the request many times

See original GitHub issue

Bug description

I use prisma middleware function along with Apollo , nexus and nexus plugin prisma

When i try to fetch something using graphql and prisma i have realized that the request is being incremented by one every time

have a look at this picture

image

here is my context

export const createContext = async (ctx: any): Promise<Context> => {
  let userId: number
  let tenant = ctx.req.get('tenant')
  let tokenValid: boolean = false
  let organizationID: number = ctx.req.get('organizationID')

   ////// here are some of authentication stuff (not related to the issue )

  //#region Prisma Middleware
//Prisma is the ORM i use
// I use prisma middleware to inject some of arguments inside my queries automatically

  prisma.$use(async (args, next) => {

    //// some inejection stuff (not related to the issue )

    console.log('PRISMA MIDDLEWARE FINISHED : ',JSON.stringify(args.args)) // i use console.log for loggin purposes 
    return next(args)
  })
  //#endregion
  return {
    ...ctx,
    prisma,
    pubsub,
    userId,
    organizationID,
    tokenValid,
  }
}

here is my apollo server constant

export const server = new ApolloServer({
  schema: applyMiddleware(schema, permissions), // apply graphql-shield rules
  context: createContext, // this is the createContext method mentioned in the a
  playground: true,
  tracing: isDev(),
  introspection: true,
  debug: isDev(),
  cors: true,
})

How to reproduce

  1. Try forking this library https://github.com/ryands17/nexus-auth
  2. Add prisma.$use function in the createContext method
  3. At the end of the if the prisma.$end , Add console.log function
  4. run the apollo server using yarn dev
  5. try to run any graphql query
  6. Watch the console output

Expected behavior

To have one request done only

Prisma information

prisma schema

generator prisma {
  provider        = "prisma-client-js"
  previewFeatures = ["orderByRelation"]
  binaryTargets   = ["native"]
}

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

model organizations {
  id                 Int        @id @default(autoincrement())
  ORGANAIZATION_NAME String     @unique
  ORGANAIZATION_CODE String     @unique
  CREATED_ON         DateTime   @default(now())
  MODIFIED_ON        DateTime?
  IS_ACTIVE          Boolean    @default(true)
  users              users[]
  vehicles           vehicles[]
}

model users {
  id                                   Int            @id @default(autoincrement())
  ORGANIZATION_ID                      Int?
  USERNAME                             String
  PASSWORD                             String
  FIRST_NAME                           String?
  LAST_NAME                            String?
  PHONE                                String?
  EMAIL                                String?
  IS_ACTIVE                            Boolean?       @default(true)
  CREATED_ON                           DateTime?      @default(now())
  MODIFIED_ON                          DateTime?
  TYPE_ID                              Int?
  CREATED_BY                           Int?
  MODIFIED_BY                          Int?
  users_usersTousers_CREATED_BY        users?         @relation("usersTousers_CREATED_BY", fields: [CREATED_BY], references: [id])
  users_usersTousers_MODIFIED_BY       users?         @relation("usersTousers_MODIFIED_BY", fields: [MODIFIED_BY], references: [id])
  organizations                        organizations? @relation(fields: [ORGANIZATION_ID], references: [id])
  other_users_usersTousers_CREATED_BY  users[]        @relation("usersTousers_CREATED_BY")
  other_users_usersTousers_MODIFIED_BY users[]        @relation("usersTousers_MODIFIED_BY")
  vehicles_usersTovehicles_CREATED_BY  vehicles[]     @relation("usersTovehicles_CREATED_BY")
  vehicles_usersTovehicles_MODIFIED_BY vehicles[]     @relation("usersTovehicles_MODIFIED_BY")
}

model vehicles {
  id                                Int            @id @default(autoincrement())
  VIN                               String?
  ORGANIZATION_ID                   Int?
  REGISTRATION_PLATE                String?
  PLATE_CODE                        String?
  PLATE_SOURCE                      String?
  VEHICLE_MAKE                      String?
  VEHICLE_MODEL                     String?
  VEHICLE_ORIGIN                    String?
  VEHICLE_YEAR                      String?
  VEHICLE_COLOR                     String?
  FUEL_CAPACITY                     String?
  FUEL_TYPE                         String?
  FUEL_CONSUMPTION                  String?
  MILEAGE                           Int?
  SEATING_CAPACITY                  String?
  PURCHASE_PRICE                    String?
  PURCHASE_DATE                     String?
  DEPRECIATION_PERCENTAGE           String?
  SALE_PRICE                        String?
  SALE_DATE                         String?
  OWNER_NAME                        String?
  OWNER_NATIONALITY                 String?
  LICENSE_ISSUED_DATE               DateTime?
  LICENSE_EXPIRY_DATE               DateTime?
  INSURANCE_EXPIRY_DATE             DateTime?
  CREATED_BY                        Int?
  CREATED_ON                        DateTime?      @default(now())
  MODIFIED_BY                       Int?
  MODIFIED_ON                       DateTime?
  users_usersTovehicles_CREATED_BY  users?         @relation("usersTovehicles_CREATED_BY", fields: [CREATED_BY], references: [id])
  users_usersTovehicles_MODIFIED_BY users?         @relation("usersTovehicles_MODIFIED_BY", fields: [MODIFIED_BY], references: [id])
  organizations                     organizations? @relation(fields: [ORGANIZATION_ID], references: [id])

  @@unique([ORGANIZATION_ID, REGISTRATION_PLATE], name: "vehiclesORGANIZATION_ID_REGISTRATION_PLATE_unique")
  @@unique([ORGANIZATION_ID, VIN], name: "vehiclesORGANIZATION_ID_VIN_unique")
}

prisma queries

i use nexus-plugin-prisma

Environment & setup

  • OS:
  • Database:
  • Node.js version:

OS : Windows 10 Database : PostgresSQL NodeJS : 14.15.1

“dependencies”: { “@prisma/client”: “2.23.0”, “apollo-server”: “2.24.1”, “bcrypt”: “5.0.1”, “dotenv”: “10.0.0”, “graphql”: “15.5.0”, “graphql-middleware”: “6.0.10”, “graphql-shield”: “7.5.0”, “jsonwebtoken”: “8.5.1”, “nexus”: “1.0.0”, “nexus-plugin-prisma”: “^0.35.0”, “prisma”: “2.23.0”, “randomstring”: “^1.2.1” },

Prisma Version

prisma cli : 2.14.2
prisma (in package.json) : 2.23

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
asaadaweycommented, May 31, 2021

@janpio I have made a reasearch how to check if a callback is defined or not I found this solution

i added the if statement inside the context and before defining the middleware to check if the client already have a defined callback or not

And that works i have queried a lot and the middleware logs that it has run once

0reactions
janpiocommented, May 31, 2021

Uh wait, how and why does this work?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Too many instances of PrismaClient · Issue #5103 - GitHub
Problem is, I'm using REST API routes (using NextJS) and not GraphQL, so each time there's an incoming request to a route (and...
Read more >
How to cache repetitive queries - Questions - Prisma 1 Forum
My queries are quite complex, but about 95% of it can be solved by cached data in resolvers, so prisma should do just...
Read more >
mysql - Why items repeat in Prisma pagination with orderBy?
In this case I don't think the order within the values with the same count is stable between different requests at the database...
Read more >
How can I find duplicates from databases for my PRISMA chart?
Zotero · Create a folder with subfolders for each database · Import citations into Database subfolders using either: · Include the number of...
Read more >
Prisma Cloud CSPM Automation Using Policy-as-Code
In the early days of Prisma Cloud deployment, I used to see hundreds of new alerts every ... that you don't need to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found