UNPKG

10.2 kBMarkdownView Raw
1![logo](https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/logo.png)
2
3# TypeGraphQL
4
5[![npm version](https://badge.fury.io/js/type-graphql.svg)](https://badge.fury.io/js/type-graphql)
6[![Build Status](https://travis-ci.com/MichalLytek/type-graphql.svg?branch=master)](https://travis-ci.com/MichalLytek/type-graphql)
7[![codecov](https://codecov.io/gh/MichalLytek/type-graphql/branch/master/graph/badge.svg)](https://codecov.io/gh/MichalLytek/type-graphql)
8[![dependencies](https://david-dm.org/MichalLytek/type-graphql/status.svg)](https://david-dm.org/MichalLytek/type-graphql)
9[![install size](https://packagephobia.now.sh/badge?p=type-graphql)](https://packagephobia.now.sh/result?p=type-graphql)
10[![gitter](https://badges.gitter.im/type-graphql.svg)](https://gitter.im/type-graphql?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
11
12Create GraphQL schema and resolvers with TypeScript, using classes and decorators!
13
14[**https://typegraphql.com/**](https://typegraphql.com/)
15<br>
16<br>
17[![](https://opencollective.com/typegraphql/donate/button.png?color=white)](https://opencollective.com/typegraphql)
18
19## Introduction
20
21**TypeGraphQL** makes developing GraphQL APIs an enjoyable process, i.e. by defining the schema using only classes and a bit of decorator magic.
22
23So, to create types like object type or input type, we use a kind of DTO classes.
24For example, to declare `Recipe` type we simply create a class and annotate it with decorators:
25
26```js
27@ObjectType()
28class Recipe {
29 @Field(type => ID)
30 id: string;
31
32 @Field()
33 title: string;
34
35 @Field(type => [Rate])
36 ratings: Rate[];
37
38 @Field({ nullable: true })
39 averageRating?: number;
40}
41```
42
43And we get the corresponding part of the schema in SDL:
44
45```graphql
46type Recipe {
47 id: ID!
48 title: String!
49 ratings: [Rate!]!
50 averageRating: Float
51}
52```
53
54Then we can create queries, mutations and field resolvers. For this purpose we use controller-like classes that are called "resolvers" by convention. We can also use awesome features like dependency injection and auth guards:
55
56```js
57@Resolver(Recipe)
58class RecipeResolver {
59 // dependency injection
60 constructor(private recipeService: RecipeService) {}
61
62 @Query(returns => [Recipe])
63 recipes() {
64 return this.recipeService.findAll();
65 }
66
67 @Mutation()
68 @Authorized(Roles.Admin) // auth guard
69 removeRecipe(@Arg("id") id: string): boolean {
70 return this.recipeService.removeById(id);
71 }
72
73 @FieldResolver()
74 averageRating(@Root() recipe: Recipe) {
75 return recipe.ratings.reduce((a, b) => a + b, 0) / recipe.ratings.length;
76 }
77}
78```
79
80And in this simple way we get this part of the schema in SDL:
81
82```graphql
83type Query {
84 recipes: [Recipe!]!
85}
86
87type Mutation {
88 removeRecipe(id: String!): Boolean!
89}
90```
91
92## Motivation
93
94We all know that GraphQL is great and solves many problems we have with REST APIs, like overfetching and underfetching. But developing a GraphQL API in Node.js with TypeScript is sometimes a bit of a pain. Why? Let's take a look at the steps we usually have to take.
95
96First, we create all the GraphQL types in `schema.gql` using SDL. Then we create our data models using [ORM classes](https://github.com/typeorm/typeorm), which represent our db entities. Then we start to write resolvers for our queries, mutations and fields, but this forces us to first create TS interfaces for all arguments, inputs, and even object types.
97
98Only then can we actually implement the resolvers using weird generic signatures and manually performing common tasks, like validation, authorization and loading dependencies:
99
100```js
101export const getRecipesResolver: GraphQLFieldResolver<void, Context, GetRecipesArgs> =
102 async (_, args, ctx) => {
103 // common tasks repeatable for almost every resolver
104 const repository = TypeORM.getRepository(Recipe);
105 const auth = Container.get(AuthService);
106 await joi.validate(getRecipesSchema, args);
107 if (!auth.check(ctx.user)) {
108 throw new NotAuthorizedError();
109 }
110
111 // our business logic, e.g.:
112 return repository.find({ skip: args.offset, take: args.limit });
113 };
114```
115
116The biggest problem is redundancy in our codebase, which makes it difficult to keep things in sync. To add a new field to our entity, we have to jump through all the files - modify an entity class, the schema, as well as the interface. The same goes for inputs or arguments. It's easy to forget to update one piece or make a mistake with a single type. Also, what if we've made a typo in field name? The rename feature (F2) won't work correctly.
117
118Tools like [GraphQL Code Generator](https://github.com/dotansimha/graphql-code-generator) or [graphqlgen](https://github.com/prisma/graphqlgen) only solve the first part - they generate the corresponding interfaces (and resolvers skeletons) for our GraphQL schema but they don't fix the schema <--> models redundancy and developer experience (F2 rename won't work, you have to remember about the codegen watch task in background, etc.), as well as common tasks like validation, authorization, etc.
119
120**TypeGraphQL** comes to address these issues, based on experience from a few years of developing GraphQL APIs in TypeScript. The main idea is to have only one source of truth by defining the schema using classes and some help from decorators. Additional features like dependency injection, validation and auth guards help with common tasks that normally we would have to handle ourselves.
121
122## Documentation
123
124The documentation, installation guide, detailed description of the API and all of its features is [available on the website](https://typegraphql.com/).
125
126### Getting started
127
128A full getting started guide with a simple walkthrough (tutorial) can be found at [getting started docs](https://typegraphql.com/docs/getting-started.html).
129
130### Video tutorial
131
132If you prefer video tutorials, you can watch [Ben Awad](https://github.com/benawad)'s [TypeGraphQL video series](https://www.youtube.com/playlist?list=PLN3n1USn4xlma1bBu3Tloe4NyYn9Ko8Gs) on YouTube.
133
134### Examples
135
136You can also check the [examples folder](https://github.com/MichalLytek/type-graphql/tree/master/examples) in this repository for more examples of usage: simple fields resolvers, DI Container support, TypeORM integration, automatic validation, etc.
137
138The [Tests folder](https://github.com/MichalLytek/type-graphql/tree/master/tests) might also give you some tips how to get various things done.
139
140## The future
141
142The currently released version is a stable 1.0.0 release. It is well tested (95% coverage, 428 test cases) and has most of the planned features already implemented. Plenty of companies and independent developers are using it in production with success.
143
144However, there are also plans for a lot more features like better TypeORM, Prisma and dataloader integration, custom decorators and metadata annotations support - [the full list of ideas](https://github.com/MichalLytek/type-graphql/issues?q=is%3Aissue+is%3Aopen+label%3A"Enhancement+%3Anew%3A") is available on the GitHub repo. You can also keep track of [development's progress on project board](https://github.com/MichalLytek/type-graphql/projects/1).
145
146If you have any interesting feature requests, feel free to open an issue on GitHub so we can discuss that!
147
148## Support
149
150TypeGraphQL is an MIT-licensed open source project. This framework is a result of the tremendous amount of work - sleepless nights, busy evenings and weekends.
151
152It doesn't have a large company that sits behind - its ongoing development is possible only thanks to the support by the community.
153
154[![](https://opencollective.com/typegraphql/donate/button.png?color=blue)](https://opencollective.com/typegraphql)
155
156### Gold Sponsors 🏆
157
158| [<img src="https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/blue_receipt.gif" width="450">](http://career.bluereceipt.co/) | [<img src="https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/ecad.png" width="200">](https://www.ecadlabs.com/) |
159| :---: | :---: |
160| [**BlueReceipt**](http://career.bluereceipt.co/) | [**ECAD Labs**](https://www.ecadlabs.com/) |
161
162> Please ask your company to support this open source project by [becoming a gold sponsor](https://opencollective.com/typegraphql/contribute/gold-sponsors-8340) and getting a premium technical support from our core contributors.
163
164### Silver Sponsors 🥈
165
166| [<img src="https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/gorrion.png" width="250">](https://gorrion.io/) | [<img src="https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/mr-yum.png" width="100">](https://www.mryum.com/) |
167| :---: | :---: |
168| [**Gorrion Software House**](https://gorrion.io/) | [**Mr Yum**](https://www.mryum.com/) |
169
170### Bronze Sponsors 🥉
171
172| [<img src="https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/live-graphics-system.png" width="60">](https://www.ligrsystems.com/) | [<img src="https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/lifex.png" width="75">](https://www.joinlifex.com/) | [<img src="https://raw.githubusercontent.com/MichalLytek/type-graphql/master/img/swiss-mentor.png" width="125">](https://www.swissmentor.com/) |
173| :---: | :---: | :---: |
174| [**Live Graphic Systems**](https://www.ligrsystems.com/) | [**LifeX Aps**](https://www.joinlifex.com/) | [**SwissMentor**](https://www.swissmentor.com/) |
175
176[![Become a Sponsor](https://opencollective.com/static/images/become_sponsor.svg)](https://opencollective.com/typegraphql)
177
178### Members 💪 and Backers ☕
179
180[![](https://opencollective.com/typegraphql/sponsors.svg?width=890&button=false)](https://opencollective.com/typegraphql#contributors)
181[![](https://opencollective.com/typegraphql/backers.svg?width=890&button=false)](https://opencollective.com/typegraphql#contributors)
182
183## Want to help?
184
185Want to file a bug, contribute some code, or improve documentation? Great! Please read our
186guidelines for [contributing][contributing] and then check out one of our [help wanted issues](https://github.com/MichalLytek/type-graphql/labels/Help%20Wanted%20%3Asos%3A).
187
188[contributing]: https://github.com/MichalLytek/type-graphql/blob/master/CONTRIBUTING.md