如何设置Apollo GraphQL服务器接受对象作为突变变量?

时间:2018-10-18 04:37:54

标签: graphql apollo apollo-server

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

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)"
            ]
          }
        }
      }
    ]
  }
}

任何想法如何正确地做到这一点?

1 个答案:

答案 0 :(得分:4)

您需要使用ShopLocation而不是input来创建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
}