TypeGraphQL
Create GraphQL resolvers and schemas with TypeScript!
Design Goals
We all love GraphQL but creating GraphQL API with TypeScript is a bit of pain. We have to mantain separate GQL schemas using SDL or JS API and keep the related TypeScript interfaces in sync with them. We also have separate ORM classes representing our db entities. This duplication is a really bad developer experience.
What if I told you that you can have only one source of truth thanks to a little addition of decorators magic? Interested? So take a look at the quick intro to TypeGraphQL!
Getting started
Let's start at the begining with an example.
We have API for cooking recipes and we love using GraphQL for it.
At first we will create the Recipe
type, which is the foundations of our API:
@ @ readonly id: string; @ title: string; @ description?: string; @ ratings: Rate; @ averageRating: number;
Take a look at the decorators:
@GraphQLObjectType()
marks the class as theobject
shape known from GraphQL SDL astype
@Field()
marks the property as the object's field - it is also used to collect type metadata from TypeScript reflection system- the parameter function in decorator
@Field(type => ID)
is used to declare the GraphQL scalar type like the builit-inID
- we also have to declare
(type => Rate)
because of limitation of type reflection - emited type ofratings
property isArray
, so we need to know what is the type of items in the array
This will generate GraphQL type corresponding to this:
type Recipe { id: ID! title: String! description: String ratings: [Rate]! averageRating: Float!}
Next, we need to define what is the Rate
type:
@ @ value: number; @ date: Date; @ user: User;
Again, take a look at @Field(type => Int)
decorator - Javascript doesn't have integers so we have to mark that our number type will be Int
, not Float
(which is number
by default).
So, as we have the base of our recipe related types, let's create a resolver!
We will start by creating a class with apropiate decorator:
@ // we will implement this later
@GraphQLResolver
marks our class as a resolver of type Recipe
(type info is needed for attaching field resolver to correct type).
Now let's create our first query:
@ {} @ async : Promise<Recipe | undefined> return thisrecipeRepository;
- our query needs to communicate with database, so we declare the repository in constructor and the DI framework will do the magic and injects the instance to our resolver
@Query
decorator marks the class method as the query (who would have thought?)- our method is async, so we can't infer the return type from reflection system - we need to define it as
(returnType => Recipe)
and also mark it as nullable becausefindOneById
might not return the recipe (no document with the id in DB) @Args()
marks the parameter as query arguments object, whereFindRecipeArgs
define it's fields - this will be injected in this place to this method
So, how the FindRecipeArgs
looks like?
@ @ recipeId: string;
This two will generate corresponding graphql schema:
type Query { recipe(recipeId: ID!): Recipe}
It is great, isn't it? 😃
Ok, let's add another query:
// ... @ : Promise<Array<Recipe>> return thisrecipeRepository;
As you can see, the function parameter name @Query(returnType => Recipe)
is only the convention and if you want, you can use the shorthand syntax like @Query(() => Recipe)
which might be quite less readable for someone. We need to declare it as a function to help resolve circular dependencies.
Also, remember to declare { array: true }
when your method is async or returns the Promise<Array<T>>
.
So now we have two queries in our schema:
type Query { recipe(recipeId: ID!): Recipe recipes: [Recipe]!}
Now let's move to the mutations:
// ... @ async // implementation...
- we declare the method as mutation using the
@Mutation()
with return type function syntax - the
@Arg()
decorator let's you declare single argument of the mutation - for complex arguments you can use as input types like
RateInput
in this case - injecting the context is also possible - using
@Context()
decorator, so you have an access torequest
oruser
data - whatever you define on server settings
Here's how RateInput
type looks:
@ @ recipeId: string; @ value: number;
@GraphQLInputType()
marks the class as the input
in SDL, in oposite to type
or scalar
The corresponding GraphQL schema:
input RateInput { recipeId: ID! value: Int!}
And the rate mutation definition:
type Mutation { rate(rate: RateInput!): Recipe!}
The last one we discuss now is the field resolver. As we declared earlier, we store array of ratings in our recipe documents and we want to expose the average rating value.
So all we need is to decorate the method with @FieldResolver()
and the method parameter with @Root()
decorator with the root value type of Recipe
- as simple as that!
// ... @ // implementation...
The whole RecipeResolver
we discussed above with sample implementation of methods looks like this:
@ {} @ return thisrecipeRepository; @ : Promise<Array<Recipe>> return thisrecipeRepository; @ async // find the document const recipe = await thisrecipeRepository; if !recipe throw "Invalid recipe ID"; // update the document reciperatings; // and save it return thisrecipeRepository; @ const ratingsCount = reciperatingslength; const ratingsSum = reciperatings ; return ratingsCount ? ratingsSum / ratingsCount : 0;
As I mentioned, in real life we want to reuse as much TypeScript definition as we can. So the GQL type classes would be also reused by ORM and the inputs/params could be validated:
; @@ @ @ readonly id: ObjectId; @ @ title: string; @ @ description: string; @ @ ratings: Rate; // note that this field is not stored in DB @ averageRating: number; // and this one is not exposed by GraphQL @ creationDate: Date;
; @ @ @ recipeId: string; @ @ @ value: number;
Of course TypeGraphQL will validate the input and params with class-validator
for you too! (in near future 😉)
Work in progress
Currently released version is an early alpha. However it's working quite well, so please feel free to test it and experiment with it.
More feedback = less bugs thanks to you! 😃
Also, you can find more examples of usage in tests
folder - there are things like simple field resolvers and many more!
Roadmap
You can keep track of development's progress on project board.
Stay tuned and come back later for more! 😉