简体   繁体   中英

How can a graphql mutation accept an array of arguments with apollo server express?

I'm creating a shopping cart in my frontend, and I want to pass all the items in the shopping cart as an array to my mutation addLicense on my backend, so I don't have to make multiple API calls. Is this possible? If so, how, or what are my options?

I've tried to add square brackets around the arguments like this

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

I've also tried to set the object type as an argument

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

First attempt throws this error

/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)

The other attempt throws this error

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

your mutation:

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

your interface input:

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

whatever you give back:

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

I got some advices over at the GraphQL Slack. I solved it by adding a new Input Type.

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

I was then able to add my mutation like so

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM