🎉 New release for Pusher Chatkit - Webhooks! Extend your in-app chat functionality
Hide
We're hiring
Products

Channels

Beams

Chatkit

DocsTutorialsSupportCareersPusher Blog
Sign InSign Up
Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Sign InSign Up

Getting started with GraphQL and TypeScript

  • Chimezie Enyinnaya
February 13th, 2019
You will need Node and TypeScript installed on your machine.

TypeScript is a superset of JavaScript, and its adoption has skyrocketed in recent years, as many apps are now being rewritten in it. If you have ever created a GraphQL server with TypeScript, then you would know it’s not as straightforward as in the JavaScript counterpart. So in this tutorial, I'll be showing you how to use TypeScript with GraphQL using TypeGraphQL. For the purpose of demonstration, we'll be rebuilding the GraphQL server that was built in the Getting up and running with GraphQL tutorial, which is a simple task manager.

Prerequisites

This tutorial assumes the following:

  • Node.js and NPM installed on your computer
  • Basic knowledge of GraphQL
  • Basic knowledge of TypeScript
  • TypeScript installed on your computer, which you can get from the official website

What’s TypeGraphQL?

TypeGraphQL is a framework building GraphQL APIs in Node.js. It makes use of TypeScript classes and decorators for defining GraphQL schema and types as well as resolvers. With TypeGraphQL, we don’t need to manually define types in SDL or create interfaces for our GraphQL schema. TypeGraphQL allows us to have only one source of truth, that way reducing field type mismatches, typos etc.

Another interesting thing about TypeGraphQL is how well it integrates with decorator-based libraries, like TypeORM, sequelize-typescript or Typegoose. This allows us to define both the GraphQL type and the entity in a single class, so we don’t need to edit multiple files to add or rename some properties.

Getting started

To get started with TypeGraphQL, we need to first install it along with its dependencies. We’ll start by creating a new project:

    $ mkdir graphql-typescript
    $ cd graphql-typescript
    $ npm init -y

Then we install TypeGraphQL:

    $ npm install type-graphql

Next, we need to install TypeScript as a dev-dependency as well as types for Node.js:

    $ npm install typescript @types/node --save-dev

TypeGraphQL requires the reflect-metadata shim, so we need to install that as well:

    $ npm install reflect-metadata

Next, we need to define some TypeScript configurations for our project. Create a tsconfig.json file within the project’s root directory, and paste the snippet below into it:

    // tsconfig.json

    {
      "compilerOptions": {
        "target": "es2016",
        "module": "commonjs",
        "lib": ["dom", "es2016", "esnext.asynciterable"],
        "moduleResolution": "node",
        "outDir": "./dist",
        "strict": true,
        "strictPropertyInitialization": false,
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
      },
      "include": ["./src/**/*"]
    }

If you have ever worked with TypeScript before (which this tutorial assumes), then you should be familiar with some of the settings above. Since TypeGraphQL makes extensive use of decorators, which are an experimental feature of TypeScript, we need to set both emitDecoratorMetadata and experimentalDecorators as true. Also, we need to add esnext.asynciterable to the list of library files, since graphql-subscription uses AsyncIterator.

Defining the GraphQL schema

We can start defining the schema for our GraphQL server. Create a new src directory, then within it, create a new schemas directory. Inside the schemas directory, create a Project.ts file and add the following code in it:

    // src/schemas/Project.ts

    import { Field, Int, ObjectType } from "type-graphql";
    import Task from "./Task";

    @ObjectType()
    export default class Project {
      @Field(type => Int)
      id: number;

      @Field()
      name: string;

      @Field(type => [Task])
      tasks: Task[];
    }

We define a Project class and use the @ObjectType() decorator to define it as a GraphQL type. The Project type has three fields: id, name and tasks. We use the @Field decorator to define these fields. The @Field decorator can also accept optional arguments. We can pass to it the type the field should be or an object containing other options we want for the field. We explicitly set the type of the id field to be Int while tasks is an array of the type Task (which we’ll create shortly).

Next, let’s define the schema for the Task type. Inside the schemas directory, create a Task.ts file and add the following code in it:

    // src/schemas/Task.ts

    import { Field, Int, ObjectType } from "type-graphql";
    import Project from "./Project";

    @ObjectType()
    export default class Task {
      @Field(type => Int)
      id: number;

      @Field()
      title: string;

      @Field(type => Project)
      project: Project;

      @Field()
      completed: boolean;
    }

This is pretty similar to the Project schema. With our schema defined, we can move on to creating the resolvers.

Adding sample data

Before we get to the resolvers, let’s quickly define some sample data we’ll be using to test out our GraphQL server. Create a data.ts file directly inside the src directory, and paste the snippet below into it:

    // src/data.ts

    export interface ProjectData {
      id: number;
      name: string;
    }

    export interface TaskData {
      id: number;
      title: string;
      completed: boolean;
      project_id: number;
    }

    export const projects: ProjectData[] = [
      { id: 1, name: "Learn React Native" },
      { id: 2, name: "Workout" },
    ];

    export const tasks: TaskData[] = [
      { id: 1, title: "Install Node", completed: true, project_id: 1 },
      { id: 2, title: "Install React Native CLI:", completed: false, project_id: 1},
      { id: 3, title: "Install Xcode", completed: false, project_id: 1 },
      { id: 4, title: "Morning Jog", completed: true, project_id: 2 },
      { id: 5, title: "Visit the gym", completed: false, project_id: 2 },
    ];

Creating the resolvers

Create a new resolvers directory inside the src directory. Inside the resolvers directory, create a ProjectResolver.ts file and paste the code below in it:

    // src/resolvers/ProjectResolver.ts

    import { Arg, FieldResolver, Query, Resolver, Root } from "type-graphql";
    import { projects, tasks, ProjectData } from "../data";
    import Project from "../schemas/Project";

    @Resolver(of => Project)
    export default class {
      @Query(returns => Project, { nullable: true })
      projectByName(@Arg("name") name: string): ProjectData | undefined {
        return projects.find(project => project.name === name);
      }

      @FieldResolver()
      tasks(@Root() projectData: ProjectData) {
        return tasks.filter(task => {
          return task.project_id === projectData.id;
        });
      }
    }

We use the @Resolver() decorator to define the class as a resolver, then pass to the decorator that we want it to be of the Project type. Then we create our first query, which is projectByName, using the @Query() decorator. The @Query decorator accepts two arguments: the return type of the query and an object containing other options which we want for the query. In our case, we want the query to return a Project and it can return null as well. The projectByName query accepts a single argument (name of the project), which we can get using the @Arg decorator. Then we use find() on the projects array to find a project by its name and simply return it.

Since the Project type has a tasks field, which is a custom field, we need to tell GraphQL how to resolve the field. We can do that using the @FieldResolver() decorator. We are getting the object that contains the result returned from the root or parent field (which will be the project in this case) using the @Root() decorator.

In the same vein, let’s create the resolvers for the Task type. Inside the resolvers directory, create a TaskResolver.ts file and paste the code below in it:

    // src/resolvers/TaskResolver.ts

    import { Arg, FieldResolver, Mutation, Query, Resolver, Root } from "type-graphql";
    import { projects, tasks, TaskData } from "../data";
    import Task from "../schemas/Task";

    @Resolver(of => Task)
    export default class {
      @Query(returns => [Task])
      fetchTasks(): TaskData[] {
        return tasks;
      }

      @Query(returns => Task, { nullable: true })
      getTask(@Arg("id") id: number): TaskData | undefined {
        return tasks.find(task => task.id === id);
      }

      @Mutation(returns => Task)
      markAsCompleted(@Arg("taskId") taskId: number): TaskData {
        const task = tasks.find(task => {
          return task.id === taskId;
        });
        if (!task) {
          throw new Error(`Couldn't find the task with id ${taskId}`);
        }
        if (task.completed === true) {
          throw new Error(`Task with id ${taskId} is already completed`);
        }
        task.completed = true;
        return task;
      }

      @FieldResolver()
      project(@Root() taskData: TaskData) {
        return projects.find(project => {
          return project.id === taskData.project_id;
        });
      }
    }

We define two queries: fetchTasks and getTask. The fetchTasks simply returns an array of all the tasks that have been created. The getTask query is pretty similar to the projectByName query. Then we define a mutation for marking a task as completed, using the @Mutation. This mutation will also return a Task. Firstly, we get the task that matches the supplied taskId. If we can’t find a match, we simply throw an appropriate error. If the task has already been marked as completed, again, we throw an appropriate error. Otherwise, we set the task completed value to true and lastly return the task.

Just as we did with the Project type, we define how we want to resolve the project field.

Building the GraphQL server

With everything in place, all that is left now is to tie them together by building a GraphQL server. We will be using graphql-yoga for building our GraphQL server. First, let’s install it:

    $ npm install graphql-yoga

With that installed, create an index.ts file directly inside the src directory, and paste the code below in it:

    // src/index.ts

    import { GraphQLServer } from "graphql-yoga";
    import "reflect-metadata";
    import { buildSchema } from "type-graphql";
    import ProjectResolver from "./resolvers/ProjectResolver";
    import TaskResolver from "./resolvers/TaskResolver";

    async function bootstrap() {
      const schema = await buildSchema({
        resolvers: [ProjectResolver, TaskResolver],
        emitSchemaFile: true,
      });

      const server = new GraphQLServer({
        schema,
      });

      server.start(() => console.log("Server is running on http://localhost:4000"));
    }

    bootstrap();

Since we need to build our schema first before making use of it in our GraphQL server, we create an async function, which we call bootstrap() (you can name it however you like). Using the buildSchema() from type-graphql, we pass to it our resolvers and we set emitSchemaFile to true (more on this shortly). Once the schema has been built, we instantiate a new GraphQL server and pass to it the schema. Then we start the server. Lastly, we call bootstrap().

Sometimes, we might need to see or inspect the schema in SDL (Schema Definition Language) that TypeGraphQL will generate for us. One way we can achieve that is setting emitSchemaFile to true at the point of building the schema. This will generate a schema.gql file directly in project’s root directory. Of course, we can customize the path however we want.

Note: make sure to import reflect-metadata on top of your entry file (before you use/import type-graphql or your resolvers)

Testing it out

Before we start testing our GraphQL, we need to first compile our TypeScript files to JavaScript. For that, we’ll be using the TypeScript compiler. Running the command below directly from the project’s root directory:

    $ tsc

The compiled JavaScript files will be inside the dist directory, as specified in tsconfig.json. Now we can start the GraphQL server:

    $ node ./dist/index.js

The server should be running on http://localhost:4000, and we can test it out with the following query:

    # fetch all tasks

    {
      fetchTasks {
        title
        project {
          name
        }
      }
    }

Conclusion

In this tutorial, we looked at what is TypeGraphQL and it makes it easy to work with GraphQL and TypeScript. To learn more about TypeGraphQL and other advanced features it provides, do check out their official website as well as the GitHub repo.

The complete code for this tutorial is available on GitHub.

Clone the project repository
  • GraphQL
  • JavaScript
  • TypeScript
  • no pusher tech

Products

  • Channels
  • Chatkit
  • Beams

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.