Jørgen V
Jørgen V

Reputation: 776

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].

Upvotes: 0

Views: 627

Answers (2)

Jørgen V
Jørgen V

Reputation: 776

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

Upvotes: 0

Maapteh
Maapteh

Reputation: 136

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...
}

Upvotes: 1

Related Questions