有没有更好的方法来使用 Prisma Client 发出 POST 请求?

is there a better way to make a POST request with Prisma Client?

尝试发出 POST 请求但出现错误,我无法自行解释/解决。以下是重现错误的步骤:

Schema/model 模板有一个 Creative 列表和 Objective,Objective 有一个描述,Creative 有几列 - 其中两列是字符串

model Template {
  id    Int    @id @default(autoincrement())
  title String @unique @default(cuid())

  // Relation fields
  objective       Objective[]
  creative        Creative[]
  createdAt        DateTime           @default(now())
  updatedAt        DateTime           @updatedAt
}

model Objective {
  id          Int      @id @default(autoincrement())
  description String
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model Creative {
  id              Int      @id @default(autoincrement())
  owner_id        String   @default(cuid())
  campaign_id     String   @default(cuid())
  parent_c_id     String   @default(cuid())
  brandLogo       String
  brandName       String
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
}

这是我的 Post 路线。 description是从数据体中解构的,而brandName和brandLogo也是从数据体中解构的。

//postRoute
router.post("/templates", async (req, res) => {
  const { description } = req.body.data.objective;

  const { brandName, brandLogo} = req.body.data.creative;

  try {
    const template = await prisma.template.create({
      data: {
        objective: {
          create: description
        },
        creative: {
          create: {
            brandName,
            brandLogo,
          }
        }
      },
      include: {
        objective: true,
        creative: true
      }
    });
    res.status(200).json({ data: template, error: "", status: 200 });
  } catch (error) {
    console.log(error);
    res.status(500).json({ data: {}, error: error, status: 500 });
  }
});


这里是我用的测试数据

{
    "data": {
      "objective":{
          "description": "This is a teesc for obj"
      },
      "creative": {
          "brandName": "This is a test bndname",
          "brandLogo": "www.test333.com/jpg"
      }
  }
}

最后,这是我得到的错误(部分)

{
    query_validation_error: 'Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateCreateInput.objective.ObjectiveCreateNestedManyWithoutTemplateInput.create`: Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateCreateInput.objective.ObjectiveCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: List([String("This is a teesc for obj")]), want: Object(ObjectiveCreateWithoutTemplateInput), Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateCreateInput.objective.ObjectiveCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: String("This is a teesc for obj"), want: Object(ObjectiveCreateWithoutTemplateInput), Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateCreateInput.objective.ObjectiveCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: List([String("This is a teesc for obj")]), want: Object(ObjectiveUncheckedCreateWithoutTemplateInput), Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateCreateInput.objective.ObjectiveCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: String("This is a teesc for obj"), want: Object(ObjectiveUncheckedCreateWithoutTemplateInput)], Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateUncheckedCreateInput.objective.ObjectiveUncheckedCreateNestedManyWithoutTemplateInput.create`: Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateUncheckedCreateInput.objective.ObjectiveUncheckedCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: List([String("This is a teesc for obj")]), want: Object(ObjectiveCreateWithoutTemplateInput), Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateUncheckedCreateInput.objective.ObjectiveUncheckedCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: String("This is a teesc for obj"), want: Object(ObjectiveCreateWithoutTemplateInput), Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateUncheckedCreateInput.objective.ObjectiveUncheckedCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: List([String("This is a teesc for obj")]), want: Object(ObjectiveUncheckedCreateWithoutTemplateInput), Query parsing/validation error at `Mutation.createOneTemplate.data.TemplateUncheckedCreateInput.objective.ObjectiveUncheckedCreateNestedManyWithoutTemplateInput.create`: Value types mismatch. Have: String("This is a teesc for obj"), want: Object(ObjectiveUncheckedCreateWithoutTemplateInput)]]',
    query_position: 'Mutation.createOneTemplate.data'
  }

我已将您的架构修改如下:

datasource mysql {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

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

model Template {
  id    Int    @id @default(autoincrement())
  title String @unique @default(cuid())

  // Relation fields
  objectives       Objective[] @relation("objectiveTemplate")
  creatives       Creative[] @relation("creativeTemplate")
  createdAt        DateTime           @default(now())
  updatedAt        DateTime           @updatedAt
}

model Objective {
  id          Int      @id @default(autoincrement())
  description String
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
  template    Template @relation("objectiveTemplate", fields: [templateId], references: [id])
  templateId  Int
}

model Creative {
  id              Int      @id @default(autoincrement())
  owner_id        String   @default(cuid())
  campaign_id     String   @default(cuid())
  parent_c_id     String   @default(cuid())
  brandLogo       String
  brandName       String
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
  template    Template @relation("creativeTemplate",fields: [templateId], references: [id])
  templateId  Int
}

并且我执行了以下操作:

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

const saveData = async (data) => {
  const template = await prisma.template.create({
    data: {
      title: 'my template' + Math.random(),
      objectives: {
        create: [
          {
            description: 'my objective',
          },
        ],
      },
      creatives: {
        create: [
          {
            brandLogo: 'id',
            brandName: 'id',
          },
        ],
      },
    },
  })

  console.log(JSON.stringify(await prisma.template.findMany({ include: { objectives: true, creatives: true } }), null, 2));
}

saveData()

一切正常