GiraphQL
Search…
Args
Similar to the Fields Guide, the examples here will mostly be for the Query type, but the same patters can be used anywhere that arguments for fields can be defined, including both Object and Interface types.

Scalars

Scalar args can be defined a couple of different ways

Using the t.arg method

1
const Query = builder.queryType({
2
fields: (t) => ({
3
string: t.string({
4
args: {
5
string: t.arg({
6
type: 'String',
7
description: 'String arg',
8
}),
9
},
10
resolve: (parent, args) => arg.string,
11
}),
12
}),
13
});
Copied!

Using convenience methods

1
const Query = builder.queryType({
2
fields: (t) => ({
3
withArgs: t.stringList({
4
args: {
5
id: t.arg.id(),
6
int: t.arg.int(),
7
float: t.arg.float(),
8
boolean: t.arg.boolean(),
9
string: t.arg.string(),
10
idList: t.arg.idList(),
11
intList: t.arg.intList(),
12
floatList: t.arg.floatList(),
13
booleanList: t.arg.booleanList(),
14
stringList: t.arg.stringList(),
15
},
16
resolve: (root, args) => Object.keys(args),
17
}),
18
}),
19
});
Copied!

Other types

Args of non-scalar types can also be created with the t.arg method.
Valid arg types include Scalars, Enums, and Input types.
1
const LengthUnit = builder.enumType('LengthUnit', {
2
values: { Feet: {}, Meters: {} },
3
});
4
5
const Giraffe = builder.objectType('Giraffe', {
6
fields: t => ({
7
height: t.float({
8
args: {
9
unit: t.arg({
10
type: LengthUnit,
11
}),
12
},
13
resolve: (parent, args) =>
14
args.unit === 'Feet' ? parent.heightInMeters * 3.281 : parent.heightInMeters,
15
}),
16
}),
17
}));
Copied!

Required args

Arguments are optional by default, but can be made required by passing required: true in the argument options. This default can be changed in the SchemaBuilder constructor, see Changing Default Nullability.
1
const Query = builder.queryType({
2
fields: (t) => ({
3
nullableArgs: t.stringList({
4
args: {
5
optional: t.arg.string(),
6
required: t.arg.string({ required: true }),
7
requiredList: t.arg.stringList({ required: true }),
8
sparseList: t.stringList({
9
required: {
10
list: true,
11
items: false,
12
},
13
}),
14
},
15
resolve: (parent, args) => Object.keys(args),
16
}),
17
}),
18
});
Copied!
Note that by default even if a list arg is optional, the items in that list are not. The last argument in the example above shows how you can make list items optional.

Lists

To create a list argument, you can wrap the the type in an array or use one of the helpers
1
const Query = builder.queryType({
2
fields: t => ({
3
giraffeNameChecker: t.booleanList({
4
{
5
args: {
6
names: t.arg.stringList({
7
required: true,
8
})
9
moreNames: t.arg({
10
type: ['String'],
11
required: true
12
})
13
},
14
},
15
resolve: (parent, args) => {
16
return [...args.names, ...args.moreNames].filter(name => ['Gina', 'James'].includes(name)),
17
}
18
})
19
}),
20
});
Copied!
Last modified 4mo ago