GraphQL

Write an awesome doc for GraphQL. A very nice an practical one extracted from GraphQL official documentation.

View on GitHub

An overview

GraphQL named type definitions in GraphQL

Data types – Scalar

Code: https://github.com/kasir-barati/graphql-js-ts/tree/main/apps/scalar-types.

Define custom scalar types

Fetch data

Passing arguments

Code: https://github.com/kasir-barati/graphql-js-ts/blob/122a487b29ec9c4b8610fe87498dfc6bae7463e1/apps/scalar-types/src/main.ts#L16.

Define custom types – Objects

Code: https://github.com/kasir-barati/graphql-js-ts/blob/main/apps/scalar-types/src/main.ts.

Mutate data

Input Object type

In NestJS we usually have this concept of DTOs where we define incoming data’s structure for create endpoint and reuse the same DTO for the update endpoint since they accept the same stuff.

In GraphQL we can do the same thing, but within the GraphQL syntax boundaries; i.e. we can use input keyword to define our incoming data type.

[!CAUTION]

Input types can NOT have:

  • Fields that are other objects, only:
    • Basic scalar types.
    • List types.
    • Or other input types (this is the same concept of nested objects that we have in NestJS).
  • Arguments either.

[!TIP]

Naming convention for input types: add Input postfix to the base name.

Following example’s schema definition:

  1. https://github.com/kasir-barati/graphql-js-ts/blob/cc9666b59d67392a89075531dbbd960683482fb8/apps/profile/src/main.ts#L24-L29

  2. https://github.com/kasir-barati/graphql-js-ts/blob/cc9666b59d67392a89075531dbbd960683482fb8/apps/profile/src/main.ts#L44-L52

Some notes about how to send mutation queries

Code: https://github.com/kasir-barati/graphql-js-ts/tree/main/apps/profile.

Enums

enum TodoStatus {
  CREATED
  IN_PROGRESS
  COMPLETED
  ARCHIVED
  DELETED
}

Interfaces & unions

These are what you might call abstract types.

interface

union

Ref