Instead of defining GraphQL schema and THEN resolvers code, let’s write both as one thing.
Let’s learn by example
Product entity written as TypeScript class with
price fields. We also have computed field
isExpensive that returns true if
price > 50.
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.
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.
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
- Basic Express example
- Typeorm integration example
- Forward resolution — eg. query only needed db fields
- Nested mutations or queries
- Serverless eg. AWS Lambda
Thanks for reading.
Follow me on twitter.
Check out typegql library.