graphql突变如何在apollo服务器表达式中接受参数数组?

时间:2019-01-08 14:31:33

标签: javascript graphql apollo

我正在前端创建一个购物车,并且希望将购物车中的所有项目作为数组传递给后端的我的变异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].

2 个答案:

答案 0 :(得分: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...
}

答案 1 :(得分:0)

我在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!
}