75

I have this input type and I would like to add a default Value to one of the fields. I want to add 0 to the value field inside the ExampleInput.

type ExampleType {
  value: Int
  another: String
}

type Mutation {
  example(input: ExampleInput): ExampleType
}

input ExampleInput {
  value: Int
  another: String
}

Any ideas?

Adolfo
  • 1,315
  • 2
  • 14
  • 22

2 Answers2

108

It looks like the grammar allows default values on input object types, so you can declare

input ExampleInput {
  value: Int = 0
  another: String
  isAvailable: Boolean = false
}

The spec is clear that default values exist and explains how they get used (first bullet under "Input Coercion").

(Whether any specific tooling supports this is probably variable: graphql.org had an informal version of the IDL for quite a while before it was actually in the spec, and I have the impression some libraries haven't caught up to the released spec yet.)

Ozymandias
  • 2,533
  • 29
  • 33
David Maze
  • 130,717
  • 29
  • 175
  • 215
  • 2
    how to set default values in manual types declaration ? like new GraphQLObjectType({ args:{ isAdmin:{type:GraphQLBoolean} } }) how to set isAdmin to False by default? – Bakaji Dec 05 '21 at 06:57
1

In a programmatic/object-based (or code-first) approach, you can set a default value like this for the InputObjectType:

 const exampleInput = new GraphQLInputObjectType({
   name: "ExampleInput",
   fields: () => ({
     value: { type: graphql.GraphQLInt, defaultValue: 0 },
     another: { type: new GraphQLNonNull(graphql.GraphQLString) },
     isAvailable: { type: graphql.GraphQLBoolean, defaultValue: false },
   }),
 });

by using defaultValue keyword.

sha'an
  • 1,032
  • 1
  • 11
  • 24