首页 > 解决方案 > 如何设置 Apollo GraphQL 服务器以接受一个对象作为突变的变量?

问题描述

目前,我正在尝试将对象作为变量传递给突变,如下所示:

type ShopLocation {
  lane1: String
  lane2: String
  city: String
  postalCode: String
  country: String
}

type ShopResponse {
  statusCode: Int
  messageCode: String
  data: String
}

type Mutation {
  createShop(
    name: String
    email: String
    location: ShopLocation
  ): ShopResponse
}

但我收到以下错误:

{
  "error": {
    "errors": [
      {
        "message": "The type of Mutation.createShop(location:) must be Input Type but got: ShopLocation.",
        "extensions": {
          "code": "GRAPHQL_VALIDATION_FAILED",
          "exception": {
            "stacktrace": [
              "Error: The type of Mutation.createShop(location:) must be Input Type but got: ShopLocation.",
              "    at assertValidSchema (.../node_modules/graphql/type/validate.js:71:11)",
              "    at Object.validate (.../node_modules/graphql/validation/validate.js:55:35)",
              "    at Promise.resolve.then (.../node_modules/apollo-server-core/src/runQuery.ts:188:30)",
              "    at <anonymous>",
              "    at process._tickDomainCallback (internal/process/next_tick.js:228:7)"
            ]
          }
        }
      }
    ]
  }
}

知道如何正确执行此操作吗?

标签: graphqlapolloapollo-server

解决方案


您需要使用ShopLocationwithinput关键字而不是type,

input ShopLocationInput {
  lane1: String
  lane2: String
  city: String
  postalCode: String
  country: String
}

type ShopResponse {
  statusCode: Int
  messageCode: String
  data: String
}

type Mutation {
  createShop(
    name: String
    email: String
    location: ShopLocationInput
  ): ShopResponse
}

推荐阅读