Lesson 52 of 56 · Typescript
GraphQL with TypeScript – `type-graphql`
Duration: 25 minutes
Install dependencies
npm i type-graphql graphql reflect-metadata
npm i -D @types/node
Add import 'reflect-metadata'; at the entry point.
Define a resolver
import { Resolver, Query, Arg, Mutation, ObjectType, Field, ID } from 'type-graphql';
@ObjectType()
class User {
@Field(() => ID)
id!: number;
@Field()
name!: string;
}
@Resolver(User)
class UserResolver {
private users: User[] = [];
@Query(() => [User])
allUsers() { return this.users; }
@Mutation(() => User)
createUser(@Arg('name') name: string): User {
const user = { id: Date.now(), name } as User;
this.users.push(user);
return user;
}
}
Bootstrap server
import { ApolloServer } from 'apollo-server';
import { buildSchema } from 'type-graphql';
async function bootstrap() {
const schema = await buildSchema({ resolvers: [UserResolver] });
const server = new ApolloServer({ schema });
const { url } = await server.listen(4000);
console.log(`🚀 GraphQL ready at ${url}`);
}
bootstrap();