GraphQL-js mutation optional arguments

10,793

Types in GraphQL are nullable by default. That means that the way you have specified the mutation at the moment makes the count optional. If you wanted a field to be mandatory you need to mark it as non null

Share:
10,793
Nicolai Schmid
Author by

Nicolai Schmid

🐧

Updated on August 10, 2022

Comments

  • Nicolai Schmid
    Nicolai Schmid almost 2 years

    how would I achieve a GraphQL Mutation in nodeJS that has arguments which are optional?

    My current mutation has an args field, but all the arguments are mandatory. Since I couldn't find anything in the documentation, I don't know how or if this is possible.

    This is my current code:

    const fakeDB = {
        count: 0
    };
    
    const schema = new GraphQLSchema({
        query: //...
        mutation: new GraphQLObjectType({
            name: 'adsF',
            fields: {
                updateCount: {
                    type: GraphQLInt,
                    args: {
                        count: { type: GraphQLInt } // I want to make this argument optional
                    },
                    resolve: (value, { count }) => {
                        // Catch if count is null or undefined
                        if (count == null) {
                            // If so just update with default
                            fakeDB.count = 5;
                        } else {
                            fakeDB.count = count
                        }
                        return fakeDB.count;
                    })
                }
            }
        })
    });
    

    Thanks for Your help!