graphql-typescript
Define and build GraphQL Schemas using typed classes
type Query { box: Box!} type Mutation { unbox(tools: [String]!): Boolean!} type Box { size: Size! content: String} type Size { height: Int! width: Int! length: Int!}
Prerequisites
Set decorator flags in your tsconfig.json
"experimentalDecorators": true,"emitDecoratorMetadata": true
Installing
npm install -S graphql
npm install -S graphql-typescript
Type Definition
@Type
Adding @Type
to a class definition defines GraphQL object type.
type Character { name: String! appearsIn: [Episode]!}
@Field
Adding @Field
to properties or methods of a @Type
decorated class defines what fields it has.
type Hello { a: String! b: [String]! c: String!}
@Mutation
Adding @Mutation
to methods of a @Type
decorated class defines a mutation. No matter which class it is in, it will come under mutation type.
type Mutation { ... a: String! b: [String]! c(world: [Int]!): String!}
@Nullable
All fields and mutations are Non-null type by default. Adding `@Nullable to fields or mutations properties make it nullable.
Hello
type Hello { hello: String}
@Input
Adding @Input
to a class definition defines a input type
An input class can only have @Field
properties.
input AddCharacterInput { name: String! age: Int!}
Scalar types
To use GraphQL default scalar types, import it from 'graphql-typescript'
Arguments
All fields of GraphQL objects type can have arguments. Methods with @Field
or @Mutation
get request query arguments from second parameter.
It needs to define a argument class. Because a purpose of this class is only typing arguments, there is no class decorator and it can have only @Field
properties.
type Mutation{ unbox(tools: [String]!): Boolean}
To use input type in argument, do like below.
input UnboxInput { tools: [String]!} type Mutation{ unbox(inputs: UnboxInput!): Boolean}
Generating GraphQL Schema
makeSchema
makeSchemarootType,
rootType
: A root type of schematypes
: Rest of types except a root type