Skip to main content

Arguments

If you wish to define arguments for a field, you must define your argument types explicitly using a type literal in your function or method signature. This allows Grats to "see" the types being used.

/** @gqlField */
myField(args: { greeting: string }): string {
return `${args.greeting} World`;
}

Functional style fields

In functional style fields, the arguments object is the second argument to the function. The first argument is the instance of the base type being extended.

/** @gqlField */
export function userById(_: Query, args: { id: string }): User {
return DB.getUserById(args.id);
}

Default values

Default values for arguments can be defined by using the = operator with destructuring. Note that you must perform the destructuring in the argument list, not in the function body:

class MyClass {
/** @gqlField */
myField({ greeting = "Hello" }: { greeting: string }): string {
return `${greeting} World`;
}
}

Deeply nested default values can also be defined:

class MyClass {
/** @gqlField */
myField({
greeting = { salutation: "Sup" },
}: {
greeting: GreetingConfig;
}): string {
return `${greeting.salutation} World`;
}
}

/** @gqlInput */
type GreetingConfig = {
salutation: string;
};

Nullable arguments

If you define your argument as nullable in your GraphQL schema, graphql-js may pass either an explicit null if the user passes an explicit null or simply not define the argument if the user omits the argument or passes it a nullable variable which ends up not being passed to the operation.

To account for this, Grats will require that any argument that is either nullable (someArg: T | null) or optional (someArg?: T) be defined as both nullable and optional: someArg?: T | null.

This ensures your resolver code handles both possible cases.

The one exception is if your argument has a default value. In that case, you may opt to mark your argument as optional but not nullable.

/** @gqlField */
export function greeting(_: Query, { name: "Max" }: { name?: string }): string {
return `Hello, ${name}`;
}

Will result in the following schema:

type Query {
greeting(name: String! = "Max"): String!
}

Note that the name argument is marked as non-nullable in the schema. This means the user may not pass an explicit null, but if the argument is omitted, the default value will be used.

Deprecated arguments

Optional arguments can be marked as @deprecated by using the @deprecated JSDoc tag:

class MyClass {
/** @gqlField */
myField(_: {
/** @deprecated Unused! */
greeting?: string;
}): string {
return `Hello World`;
}
}