graphql,当存在“添加”和“更新”突变时,如何设计输入类型?

时间:2018-07-25 11:05:54

标签: graphql graphql-js apollo-server

这是我的要求:

  1. “ add”突变,BookInput输入类型的每个字段(或称为标量)都应具有附加的类型修饰符“!”。验证非空值。这意味着当我添加一本书时,参数必须具有titleauthor字段,例如{title: "angular", author: "novaline"}

  2. “更新”突变,我想更新书的一部分字段,不想更新整本书(MongoDB文档,而且,我不希望前端通过graphql服务器整个大书突变论证以节省带宽)。这意味着book参数可以是{title: "angular"}{title: "angular", author: "novaline"}

这是我的类型定义:

const typeDefs = `
  input BookInput {
    title: String!
    author: String!
  }

  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type Query {
    books: [Book!]!
  }

  type Mutation{
    add(book: BookInput!): Book
    update(id: String!, book: BookInput!): Book
  }
`;

就目前而言,“ add”突变可以正常工作。但是,如果我通过了{title: "angular"}参数,则“更新”突变将无法通过非null检查

这是一个无法通过非空检查的突变,缺少BookInput输入类型的“作者”字段。

mutation {
  update(id: "1", book: {title: "angular"}) {
    id
    title
    author
  }
}

所以,graphql会给我一个错误:

{
  "errors": [
    {
      "message": "Field BookInput.author of required type String! was not provided.",
      "locations": [
        {
          "line": 2,
          "column": 24
        }
      ]
    }
  ]
}

如何设计BookInput输入类型?不想定义addBookInputupdateBookInput。它是重复的。

2 个答案:

答案 0 :(得分:5)

一个非常常见的模式是为每个突变设置不同的输入类型。您可能还想为每个操作创建一个变异查询。也许是这样的:

const typeDefs = `
  input AddBookInput {
    title: String!
    author: String!
  }

  input UpdateBookInput {
    # NOTE: all fields are optional for the update input 
    title: String
    author: String
  }

  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type Query {
    books: [Book!]!
  }

  type Mutation{
    addBook(input: AddBookInput!): Book
    updateBook(id: String!, input: UpdateBookInput!): Book
  }
`;

有些人还喜欢在更新输入中包含更新ID:

const typeDefs = `
  input AddBookInput {
    title: String!
    author: String!
  }

  input UpdateBookInput {
    # NOTE: all fields, except the 'id' (the selector), are optional for the update input 
    id: String!
    title: String
    author: String
  }

  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type Query {
    books: [Book!]!
  }

  type Mutation{
    addBook(input: AddBookInput!): Book
    updateBook(input: UpdateBookInput!): Book
  }
`;

最后,您可能希望对返回类型使用“有效载荷”类型-以增加灵活性(为您留出更大的空间来稍后更改返回类型,而不会破坏您的API):

const typeDefs = `
  input AddBookInput {
    title: String!
    author: String!
  }

  input UpdateBookInput {
    # NOTE: all fields, except the 'id' (the selector), are optional for the update input 
    id: String!
    title: String
    author: String
  }

  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type AddBookPayload {
    book: Book!
  }

  type UpdateBookPayload {
    book: Book!
  }

  type Query {
    books: [Book!]!
  }

  type Mutation{
    addBook(input: AddBookInput!): AddBookPayload!
    updateBook(input: UpdateBookInput!): UpdateBookPayload!
  }
`;

希望这会有所帮助!

答案 1 :(得分:0)

这是我的解决方案,我编写了一个辅助函数来生成“创建” input类型和“更新” input类型。

const { parse } = require('graphql');

/**
 * schema definition helper function - dynamic generate graphql input type
 *
 * @author https://github.com/mrdulin
 * @param {string} baseSchema
 * @param {object} options
 * @returns {string}
 */
function generateInputType(baseSchema, options) {
  const inputTypeNames = Object.keys(options);
  const schema = inputTypeNames
    .map(inputTypeName => {
      const { validator } = options[inputTypeName];
      const validatorSchema = Object.keys(validator)
        .map(field => `${field}: ${validator[field]}\n`)
        .join(' ');

      return `
      input ${inputTypeName} {
        ${baseSchema}
        ${validatorSchema}
      }
    `;
    })
    .join(' ')
    .replace(/^\s*$(?:\r\n?|\n)/gm, '');

  try {
    parse(schema);
    return schema;
  } catch (err) {
    throw new Error(`${err.message}`);
  }
}

schema.js

${generateInputType(
  `
  campaignTemplateNme: String
`,
  {
    CreateCampaignTemplateInput: {
      validator: {
        channel: 'ChannelUnionInput!',
        campaignTemplateSharedLocationIds: '[ID]!',
        campaignTemplateEditableFields: '[String]!',
        organizationId: 'ID!',
      },
    },
    UpdateCampaignTemplateInput: {
      validator: {
        channel: 'ChannelUnionInput',
        campaignTemplateSharedLocationIds: '[ID]',
        campaignTemplateEditableFields: '[String]',
        organizationId: 'ID',
      },
    },
  },
)}