Search code examples
graphqlgraphql-js

How to set argument optional in Graphql?


In my mongodb model, name is required but i want to make it optional in graphql. How can i do this?

    updateExercise: {
            type: ExerciseType,
            args: {
                id: {type: new GraphQLNonNull(GraphQLString)},
                username: {type: new GraphQLString},
                description: {type: new GraphQLString},
                duration: {type: new GraphQLInt},
                date: {type: new GraphQLString}
            },
            resolve(parent, args) {
                Exercise.findByIdAndUpdate(args.id)
                .then(exercise => {
                    exercise.username = args.username,
                    exercise.description = args.description,
                    exercise.duration = args.duration,
                    exercise.date = args.date
                    exercise.save()
                    .then( () => 'Succesfully Updated')
                    .catch( e => console.log(e) )
                })
            }
        }

Solution

  • You are misusing the findByIdAndUpdate function. It should probably be used in this way:

    const SomeType = new GraphQLObjectType({
        updateExercise: {
                type: ExerciseType,
                args: {
                    id: {type: new GraphQLNonNull(GraphQLString)},
                    username: {type: GraphQLString},
                    description: {type: GraphQLString},
                    duration: {type: GraphQLInt},
                    date: {type: GraphQLString}
                },
                resolve(parent, args) {
                    return Exercise.findByIdAndUpdate(args.id, {
                        username: args.username || undefined,
                        description: args.description,
                        duration: args.duration,
                        date: args.date
                    }).then(() => 'Succesfully Updated')
                      .catch(e => console.log(e))
                })
            }
        }
    });
    

    We use a little trick in JS to short-circuit the returned value. This will supply undefined for the username property when args.username is null. If you are in an environment where you are not sure if undefined as been reassigned you can use void 0 instead. If you are using a new TypeScript or EcmaScript version you can use the newer ?? operator instead of ||.