【问题标题】:Why is the GraphQL input type breaking the app为什么 GraphQL 输入类型会破坏应用程序
【发布时间】:2021-07-28 09:21:23
【问题描述】:

我遇到了问题。我试图在 Apollo GraphQL API 上测试一个突变。当我将单个字段用于突变类型时,它起作用了,但是当我用我创建的输入类型替换字段时,我得到一个错误。它在 NextJS 项目中,在 api 文件夹中,所以我使用的是apollo-server-micro

错误信息

工作代码

const { gql } = require("apollo-server-micro");

export const typeDefs = gql`
  type Appointment {
    id: ID!
    firstName: String
    lastName: String
    email: String
    phoneNumber: String
  }

  type Query {
    appointments: [Appointment]
    appointment(id: Int): Appointment
  }

  type Mutation {
    bookAppointment(
      firstName: String!
      lastName: String
      email: String
      phoneNumber: String
    ): Appointment
  }

  input AppointmentInput {
    firstName: String!
    lastName: String
    email: String
    phoneNumber: String
  }
`;

问题代码

const { gql } = require("apollo-server-micro");

export const typeDefs = gql`
  type Appointment {
    id: ID!
    firstName: String
    lastName: String
    email: String
    phoneNumber: String
  }

  type Query {
    appointments: [Appointment]
    appointment(id: Int): Appointment
  }

  type Mutation {
    bookAppointment(appointment: AppointmentInput): Appointment
  }

  input AppointmentInput {
    firstName: String!
    lastName: String
    email: String
    phoneNumber: String
  }
`;

解析器

export const resolvers = {
  Query: {
    appointments: async (parent, args, { prisma }) => {
      return prisma.appointment.findMany();
    },
    appointment: async (parent, args, context) => {
      return context.prisma.appointment.findUnique({ where: { id: args.id } });
    },
  },

  Mutation: {
    bookAppointment: async (parent, args, context) => {
      const id = +Math.floor(Math.random() * 5001) + 1000;
      const booking = context.prisma.appointment.create({
        data: {
          id: id,
          firstName: args.firstName,
          lastName: args.lastName,
          email: args.email,
          phoneNumber: args.phoneNumber,
        },
      });
      return booking;
    },
  },
};

【问题讨论】:

  • 突变解析器代码未更新 - 错误/缺少的参数传递到 prisma
  • 确切地说,当我运行将字段传递给输入类型 AppointmentInput 并使用输入的突变时,它不起作用。当我直接在突变中使用这些字段时,它可以工作并接受参数。今天早上在另一个项目中运行,使用常规的 react 和 Apollo 与 Prisma,它按预期工作。
  • 你的解析器是什么样的?
  • 我在上面添加了解析器,很抱歉第一次没有包含它。

标签: reactjs graphql next.js apollo-server


【解决方案1】:

您可以/应该在更改之前拥有/使用分解的变量:

const { firstName, lastName, email, phoneNumber } = args;

并简单/直接使用firstName, lastName ...

改变将是微不足道的:

const { firstName, lastName, email, phoneNumber } = args.appointment;

const { appointment: { firstName, lastName, email, phoneNumber } } = args;

...但您也可以将其全部缩短:

const booking = context.prisma.appointment.create({
  data: {
    id, ...args.appointment 
  },

【讨论】:

    猜你喜欢
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多