# GraphQL Contributors are welcome Help wanted
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
# Feature
Currently, @tsed/graphql
allows you to configure one or more GraphQL server in your project.
This package uses apollo-server-express
(opens new window) to create GraphQL server and type-graphql
(opens new window)
as decorator library.
# Installation
To begin, install the GraphQL module for TS.ED, graphql and apollo-server-testing:
Type-graphql (opens new window) requires to update your tsconfig.json
by adding extra options as following:
{
"target": "es2018",
"lib": ["es2018", "esnext.asynciterable"],
"allowSyntheticDefaultImports": true
}
2
3
4
5
Now, we can configure the Ts.ED server by importing @tsed/graphql
in your Server:
# GraphQlService
GraphQlService lets you to retrieve an instance of ApolloServer.
import {AfterRoutesInit, Service} from "@tsed/common";
import {GraphQLService} from "@tsed/graphql";
import {ApolloServer} from "apollo-server-express";
@Service()
export class UsersService implements AfterRoutesInit {
private server: ApolloServer;
constructor(private graphQLService: GraphQLService) {
}
$afterRoutesInit() {
this.server = this.graphQLService.get("server1")!;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
For more information about ApolloServer, look at its documentation here (opens new window);
# Type-graphql
# Types
We want to get the equivalent of this type described in SDL:
type Recipe {
id: ID!
title: String!
description: String
creationDate: Date!
ingredients: [String!]!
}
2
3
4
5
6
7
So we create the Recipe class with all properties and types:
class Recipe {
id: string;
title: string;
description?: string;
creationDate: Date;
ingredients: string[];
}
2
3
4
5
6
7
Then we decorate the class and its properties with decorators:
import {Field, ID, ObjectType} from "type-graphql";
@ObjectType()
export class Recipe {
@Field(type => ID)
id: string;
@Field()
title: string;
@Field({nullable: true})
description?: string;
@Field()
creationDate: Date;
@Field(type => [String])
ingredients: string[];
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
The detailed rules for when to use nullable, array and others are described in fields and types docs (opens new window).
# Resolvers
After that we want to create typical crud queries and mutation. To do that we create the resolver (controller) class that will have injected RecipeService in the constructor:
import {Inject} from "@tsed/di/src";
import {ResolverService} from "@tsed/graphql";
import {Arg, Args, Query} from "type-graphql";
import {RecipeNotFoundError} from "../errors/RecipeNotFoundError";
import {RecipesService} from "../services/RecipesService";
import {Recipe} from "../types/Recipe";
import {RecipesArgs} from "../types/RecipesArgs";
@ResolverService(Recipe)
export class RecipeResolver {
@Inject()
private recipesService: RecipesService;
@Query(returns => Recipe)
async recipe(@Arg("id") id: string) {
const recipe = await this.recipesService.findById(id);
if (recipe === undefined) {
throw new RecipeNotFoundError(id);
}
return recipe;
}
@Query(returns => [Recipe])
recipes(@Args() {skip, take}: RecipesArgs) {
return this.recipesService.findAll({skip, take});
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Data Source
Data source is one of the Apollo server features which can be used as option for your Resolver or Query. Ts.ED provides a DataSourceService decorator to declare a DataSource which will be injected to the Apollo server context.
import {DataSourceService} from "@tsed/graphql";
import {RESTDataSource} from "apollo-datasource-rest";
import {User} from "../models/User";
@DataSourceService()
export class UserDataSource extends RESTDataSource {
constructor() {
super();
this.baseURL = "https://myapi.com/api/users";
}
getUserById(id: string): Promise<User> {
return this.get(`/${id}`);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Then you can retrieve your data source through the context in your resolver like that:
import {ResolverService} from "@tsed/graphql";
import {Arg, Authorized, Ctx, Query} from "type-graphql";
import {UserDataSource} from "../datasources/UserDataSource";
import {User} from "../models/User";
@ResolverService(User)
export class UserResolver {
@Authorized()
@Query(() => User)
public async user(
@Arg("userId") userId: string,
@Ctx("dataSources") dataSources: any
): Promise<User> {
const userDataSource: UserDataSource = dataSources.userDataSource;
return userDataSource.getUserById(userId);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Testing
Now we want to test the recipe by sending a graphQL query. Here is an example to create a test server and run a query:
# Author
# Maintainers
Other topics
- Session & cookies
- Passport.js
- TypeORM
- Mongoose
- GraphQL
- Socket.io
- Swagger
- AJV
- Multer
- Serve static files
- Templating
- Throw HTTP Exceptions
- Customize 404
- AWS
- Seq
- OIDC
- Stripe
- Controllers
- Providers
- Model
- JsonMapper
- Middlewares
- Pipes
- Interceptors
- Authentication
- Hooks
- Exceptions
- Hooks
- Response Filter
- Injection scopes
- Custom providers
- Custom endpoint decorator
- Testing