【问题标题】:How can a graphql mutation accept an array of arguments with apollo server express?graphql 突变如何接受带有 apollo server express 的参数数组?
【发布时间】:2019-01-09 21:20:08
【问题描述】:

我正在我的前端创建一个购物车,我想将购物车中的所有项目作为一个数组传递给我后端的突变 addLicense,因此我不必进行多次 API 调用。这可能吗?如果是这样,怎么做,或者我有什么选择?

我尝试在这样的参数周围添加方括号

extend type Mutation {
    addLicense([
        licenseType: String!
        licenseAmount: String!
        isActive: Boolean
        expirationDate: Date!
    ]): License!
}

我也尝试将对象类型设置为参数

extend type Mutation {
    addLicense(
    license: [License]
): License!

第一次尝试抛出此错误

/app/node_modules/graphql/language/parser.js:1463
throw (0, _error.syntaxError)(lexer.source, token.start, "Expected ".concat(kind, ", found ").concat((0, _lexer.getTokenDesc)(token)));
^
GraphQLError: Syntax Error: Expected Name, found [
at syntaxError 
(/app/node_modules/graphql/error/syntaxError.js:24:10)

其他尝试抛出此错误

Error: The type of Mutation.addLicense(license:) must be Input Type but got: [License].

【问题讨论】:

    标签: javascript graphql apollo


    【解决方案1】:

    你的突变:

    type Mutation {
        """
        Add multiple items to basket
        """
        addLicenses(licenses: [License!]!): LicenseMutationBatchResult
    }
    

    你的界面输入:

    input License {
        licenseType: String!
        licenseAmount: String!
        isActive: Boolean
        expirationDate: Date!
    }
    

    无论你回馈什么:

    type LicenseMutationBatchResult {
        ...whatever you give back here...
    }
    

    【讨论】:

      【解决方案2】:

      我在 GraphQL Slack 上得到了一些建议。我通过添加一个新的输入类型解决了这个问题。

      input LicenseInput {
          id: ID
          licenseType: String!
          licenseAmount: String!
          isActive: Boolean
          expirationDate: Date
          course: String!
          organizationID: String!
          price: Int!
      }
      

      然后我可以像这样添加我的突变

      extend type Mutation {
          addLicense(
              license: [LicenseInput] <-
          ): License!
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 2017-02-07
        • 1970-01-01
        • 2019-09-01
        • 2019-02-17
        • 2022-11-09
        • 2021-04-03
        • 2018-07-02
        • 2023-03-05
        相关资源
        最近更新 更多