next.js 对象属性抛出TypeScript错误“ts(18004)”的所有Prisma DB

juud5qan  于 2023-04-11  发布在  TypeScript
关注(0)|答案(2)|浏览(199)

我正在尝试验证用户的电子邮件是否已经存在。我正在使用Prisma Client的findUnique方法。下面是我用来尝试和完成的代码:

const userWithEmail = await prisma.user.findUnique({
    where: {
      email,
    },
  });

但是我得到了一个TypeScript错误:

No value exists in scope for the shorthand property 'email'. Either declare one or provide an initializer.ts(18004)

下面是我的schema.prisma文件:

// 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"
}

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

model Restaurant {
  id          Int      @id @default(autoincrement())
  name        String
  main_img    String
  images      String[]
  description String
  price       PRICE
  opens_at    String
  closes_at   String
  slug        String   @unique
  created_at  DateTime @default(now())
  updated_at  DateTime @updatedAt
  item        Item[]
  location_id Int      @unique
  location    Location @relation(fields: [location_id], references: [id])
  cuisine_id  Int      @unique
  cuisine     Cuisine  @relation(fields: [cuisine_id], references: [id])
  review_id   Int      @unique
  reviews     Review[]
}

model Item {
  id            Int        @id @default(autoincrement())
  name          String
  price         String
  description   String
  created_at    DateTime   @default(now())
  updated_at    DateTime   @updatedAt
  restaurant_id Int
  restaurant    Restaurant @relation(fields: [restaurant_id], references: [id])
}

model Location {
  id         Int          @id @default(autoincrement())
  name       String
  restraunts Restaurant[]
  created_at DateTime     @default(now())
  updated_at DateTime     @updatedAt
}

model Cuisine {
  id         Int          @id @default(autoincrement())
  name       String
  restraunts Restaurant[]
  created_at DateTime     @default(now())
  updated_at DateTime     @updatedAt
}

model User {
  id         Int      @id @default(autoincrement())
  first_name String
  last_name  String
  city       String
  email      String   @unique
  password   String
  phone      String
  review     Review[]
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
}

model Review {
  id            Int        @id @default(autoincrement())
  first_name    String
  last_name     String
  rating        Float
  text          String
  restaurant_id Int
  restaurant    Restaurant @relation(fields: [restaurant_id], references: [id])
  user_id       Int
  user          User       @relation(fields: [user_id], references: [id])
  created_at    DateTime   @default(now())
  updated_at    DateTime   @updatedAt
}

enum PRICE {
  CHEAP
  REGULAR
  HIGH
  EXPENSIVE
}

我的route.ts文件:

import { PrismaClient } from "@prisma/client";
import { NextResponse } from "next/server";
import validator from "validator";

const prisma = new PrismaClient();

export async function POST(request: Request) {
  const body = await request.json();
  const errors: string[] = [];

  const validationSchema = [
    {
      valid: validator.isLength(body.firstName, {
        min: 1,
        max: 20,
      }),
      error: "Invalid first name.",
    },
    {
      valid: validator.isLength(body.lastName, {
        min: 1,
        max: 20,
      }),
      error: "Invalid last name.",
    },
    {
      valid: validator.isEmail(body.email),
      error: "Invalid email.",
    },
    {
      valid: validator.isMobilePhone(body.phone),
      error: "Invalid phone number.",
    },
    {
      valid: validator.isLength(body.city, {
        min: 1,
        max: 20,
      }),
      error: "Invalid city.",
    },
    {
      valid: validator.isStrongPassword(body.password),
      error: "Invalaid password.",
    },
  ];

  validationSchema.forEach((check) => {
    if (!check.valid) {
      errors.push(check.error);
    }
  });

  if (errors.length) {
    return NextResponse.json(errors[0]);
  }

  const userWithEmail = await prisma.user.findUnique({
    where: {
      email,
    },
  });
  
  return NextResponse.json({
    response: "OK",
  });
}

我正在使用Next js 13和Prisma。我做错了什么?

lh80um4z

lh80um4z1#

我认为问题在这里:

const body = await request.json();

没有request.json() .如果你使用

import { NextApiRequest } from "next";

typescript会警告你.这是NextApiRequest

export interface NextApiRequest extends IncomingMessage {
  query: Partial<{
      [key: string]: string | string[];
  }>;
  cookies: Partial<{
      [key: string]: string;
  }>;
  body: any;
  env: Env;
  preview?: boolean;
  previewData?: PreviewData;
}

它扩展了IncomingMessage,但它也没有json()属性。相反,你应该有

const { email, password } = req.body;
xoefb8l8

xoefb8l82#

也许“email”变量在方法中的作用域不同。
例如,在findUnique调用的行之前声明“email”变量,这个问题就解决了。

const email = "test@example.com"
const userWithEmail = await prisma.user.findUnique({
    where: {
      email,
    },
  });

如果您没有将email变量声明为“email”name(Ex,mailAddress),请尝试编写以下代码。

const mailAddress = "test@example.com"
const userWithEmail = await prisma.user.findUnique({
    where: {
      email: mailAddress,
    },
  });

相关问题