Types and Fields

Introduction

@foadonis/graphql uses the "code-first" approach by automatically generating your GraphQL schema based on your code.

With the following Typescript class which represents our Recipe model with fields for storing the recipe data:

class Recipe {
  declare id: string
  declare title: string
  declare averageRating: number
}

By using the provided decorators you can turn your Typescript class into a GraphQL Type:

import { ,  } from '@foadonis/graphql'

@()
class  {
  @()
  declare : string

  @()
  declare : string

  @()
  declare : number
}

Complex types

To generate the GraphQL we heavily rely on Typescript metadata to infer the type of a property. There are cases where this is not possible and require explicit type to be provided.

Nullable

import { ,  } from '@foadonis/graphql'

@()
class  {
  @()
  declare : string

  @(() => , { : true })
  declare : string | null
}

Array

import { ,  } from '@foadonis/graphql'

@()
class  {
  @(() => [])
  declare : string[]
}

Scalars

import { ,  } from '@foadonis/graphql'
import { , ,  } from 'graphql-scalars'

@()
class  {
  @(() => , { : true })
  declare : string | null

  @(() => )
  declare : any
}

Objects

import { ,  } from '@foadonis/graphql'

@()
class  {
  @()
  declare : string
}

@()
class  {
  @(() => [])
  declare : []
}

Enums

You can generate GraphQL enums using Typescript enums with the registerEnumType function. Due to typescript limitations the name and the type must be explicitly defined.

import { , ,  } from '@foadonis/graphql'

enum  {
   = 'DRAFT',
   = 'IN_REVIEW',
   = 'PUBLISHED',
}

(, {
  : 'RecipeStatus', // mandatory
})

@()
class  {
  @(() => ) // mandatory
  declare : 
}

For interoperability with databases the enum value is used. Meaning that if you want to share the types with your client you must map each key with the corresponding value.

Documentation

The description parameter on ObjectType and Field allows you to provide documentation to your GraphQL schema that will be shown in the introspection.

import { , ,  } from '@foadonis/graphql'

@({
  : 'A cooking recipe',
})
class  {
  @(() => , { : 'Unique identifier in Uuid V4 format' })
  declare : string
}

On this page