Ricerca nel sito web

node.js - La query Prisma restituisce null, quando i dati esistono


Ho creato un'app Nestjs con Prisma e GQL. Ho appena cambiato computer (da un Mac a un PC) e all'improvviso la mia mutazione login sembra aver smesso di funzionare, letteralmente l'unica... Ecco un po' di codice:

auth.resolver.ts:

@Mutation((returns) => AuthenticatedUser)
async login(
  @Context() { res }: Auth.GqlContext,
  @Args('payload', { type: () => UserLoginDto }) payload: UserLoginDto
): Promise<AuthenticatedUser> {
  const authenticatedUser = await this.authService.login(payload)
  
  res.cookie('jwt', authenticatedUser.jwt, cookieConfig)

  return authenticatedUser
}

auth.service.ts:

public async login(payload: UserLoginDto): Promise<AuthenticatedUser> {
  const { password, email } = payload

  Logger.log({ password, email })

  const user = await this.usersService.getUser(email) // returns null since the change

  Logger.log(JSON.stringify(user))

  const isValidPassword = await this.verifyPassword(user.password, password) // error is thrown here

  if (!isValidPassword) {
    throw new AuthenticationError('Password does not match')
  }

  const { id } = user

  const jwt = await this.jwtService.signAsync(
    { id, email },
    {
      secret: process.env.JWT_SECRET
    }
  )

  return {
    jwt,
    user
  }
}

users.service.ts:

public async getUser(email: string): Promise<User | null> {
  const { user } = this.prismaService

  Logger.log(email) // returns '[email '

  const temp = user.findUnique({ where: { email } }) // returns null here

  Logger.log(`PRISMA USER: ${JSON.stringify(temp)}`) // null

  return temp
}

È strano che abbia le stesse query impostate per posts e categories, ma quelle funzionano bene. Non ha nulla a che fare con JWT.

Il mio utente è anche nel DB:

Mutazione GQL completa:

mutation {
  login(payload: { email: "[email ", password: "123" }) {
    jwt
    user {
      name
      id
      email
    }
  }
}

Errore GQL:

{
  "errors": [
    {
      "message": "Cannot read property 'password' of null",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "login"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "TypeError: Cannot read property 'password' of null",
            "    at AuthService.login (H:\\work\\blog-api\\src\\auth\\auth.service.ts:25:60)",
            "    at AuthResolver.login (H:\\work\\blog-api\\src\\auth\\auth.resolver.ts:43:31)",
            "    at target (H:\\work\\blog-api\\node_modules\\@nestjs\\core\\helpers\\external-context-creator.js:77:28)",
            "    at H:\\work\\blog-api\\node_modules\\@nestjs\\core\\helpers\\external-proxy.js:9:24"
          ]
        }
      }
    }
  ],
  "data": null
}

Schema Prisma:

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

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

model Post {
  id            String     @id @default(uuid())
  title         String
  slug          String     @unique
  description   String
  relativeImage String     @map("relative_image")
  rawMdx        String     @map("raw_mdx")
  published     Boolean    @default(true)
  views         Int        @default(0)
  likes         Int        @default(0)
  createdAt     DateTime   @default(now()) @map("created_at")
  updatedAt     DateTime   @updatedAt @map("updated_at")
  categories    Category[]
}

model Category {
  id        String   @id @default(uuid())
  name      String   @unique
  color     String
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")
  posts     Post[]
}

model User {
  id        String   @id @default(uuid())
  name      String   @unique
  email     String   @unique
  password  String
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")
}

Ho anche eseguito npx prisma db pull && npx prisma generate da quando ho cambiato computer...

Aggiornamento

Dopo circa un'ora questo problema è scomparso. Se qualcuno sa perché ho avuto questo problema, mi piacerebbe sapere il motivo.

Risposta n. 1

hai provato

const tmpUser = user.findUnique({where: {email}, select: {password: true}})