Image for post
Image for post
Everything you might read below is basically included on this photo.

GraphQL + Typescript = strongly typed api schema

Instead of defining GraphQL schema and THEN resolvers code, let’s write both as one thing.

Let’s learn by example

We have Product entity written as TypeScript class with id and price fields. We also have computed field isExpensive that returns true if price > 50.

Le’ts define our first object type

Everything is strongly typed here. It’s important, as it will allow inferring GraphQL schema out of it.

Let’s move forward. Code above would give us fully functional GraphQL object type. Now let’s create schema that is using it.

Let’s add it to schema

We’ve added some root Query field called findProductById. It have some argument and it returns Product object defined previously.

Again everything (including arguments) is strongly-typed, so it’s possible to guess how GraphQL schema would look like and to generate it automatically.

Let’s generate such schema and start some Express GraphQL api server.

Let’s compile schema and create some graphql server

That’s all. Now, when we’d start server, it’ll handle query like:

As you’ve probably seen, I’m using library called typegql. It’s lib I’ve created with Prismake to help with 3 main things:

  • have graphql schema type-safe
  • have single source of truth for schema types (instead of separated graphql and resolvers definitions)
  • have types and business logic as close to each other as possible

You can check it out here.

More examples with typegql:

Image for post
Image for post
A to Z process of creating hello world api

Thanks for reading.

Follow me on twitter.

Check out typegql library.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store