To define a GraphQL field, put a @gqlField docblock directly before a:

  • method declaration;
  • method signature;
  • property declaration;
  • property signature;
  • parameter property;
  • static method;
  • function declaration;
  • arrow function declaration.

Tip

To define fields on the root types Query, Mutation or Subscription, see Root fields.

Class-based fields

When you define GraphQL types with classes or interfaces, a field can be a class property or a method:

User.ts
/** @gqlType */
class User {
  /**
   * A description of some field.
   * @gqlField
   */
  someField: string;

  constructor(someField: string) {
    this.someField = someField;
  }

  /** @gqlField */
  myField(): string {
    return "Hello World";
  }
}

A field can also be one of TypeScript's parameter properties, a shorthand for a property whose value is passed to the class's constructor:

User.ts
/** @gqlType */
class User {
  constructor(
    /** @gqlField */
    public name: string,
  ) {}
}

Note

A parameter property needs a transpiler: Node's type stripping, which runs .ts files directly, rejects it (ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX). To run your code that way, declare the property in the class and assign it in the constructor.

For more about field resolvers, see Resolver signature.

Functional style fields

If you prefer to avoid classes, you can define types with type literals. Type literals cannot define derived (resolver) fields, though. For those, define a derived field as a named, exported function. A function resolver:

  • takes an instance of the parent type as its first argument;
  • has a return type that matches the field's type;
  • is an exported, named function, whose name is the field's name.
User.ts
/** @gqlType */
type User = {
  /** @gqlField */
  firstName: string;
  /** @gqlField */
  lastName: string;
};

/** @gqlField */
export function fullName(user: User): string {
  return `${user.firstName} ${user.lastName}`;
}

Gratos uses the type of the first argument to know which type the field extends. So, as in the examples above, define a typed first argument even when you don't need the instance.

More field documentation