GraphQL TypeScript Library: A Modern Approach to APIs
GraphQL is a query language for APIs that allows clients to request only the necessary data. Combined with TypeScript, it provides a powerful type system ensuring safety and autocompletion. On pythonlib.ru, we will cover the key library for working with GraphQL in TypeScript — type-graphql, as well as alternatives.
Why TypeScript + GraphQL?
TypeScript adds static typing, which is critically important for large projects. A GraphQL schema described through TypeScript classes becomes a single source of truth: changes in the code are automatically synchronized with the API. This eliminates discrepancies between documentation and the actual server behavior.
Main Library: TypeGraphQL
type-graphql is a framework for creating GraphQL APIs in TypeScript using decorators. It follows the code-first principle: you define the schema through code, rather than through SDL (Schema Definition Language).
Installation
npm install type-graphql graphql reflect-metadataAdd to tsconfig.json:
{ "emitDecoratorMetadata": true, "experimentalDecorators": true}Example: Defining a Type and Resolver
Let's create a simple user model and a resolver to fetch data.
import { ObjectType, Field, ID, Resolver, Query } from "type-graphql";
@ObjectType()class User { @Field(() => ID) id: number;
@Field() name: string;
@Field({ nullable: true }) email?: string;}
@Resolver()class UserResolver { @Query(() => [User]) users(): User[] { return [ { id: 1, name: "Anna", email: "anna@example.com" }, { id: 2, name: "Boris", email: null } ]; }}Building and Starting the Server
import { buildSchema } from "type-graphql";import { ApolloServer } from "@apollo/server";import { startStandaloneServer } from "@apollo/server/standalone";
async function main() { const schema = await buildSchema({ resolvers: [UserResolver] });
const server = new ApolloServer({ schema }); const { url } = await startStandaloneServer(server, { listen: { port: 4000 } }); console.log(`Server running: ${url}`);}
main();Alternative Libraries
- NestJS + GraphQL — integration with a popular framework. Uses
@nestjs/graphqlbased ontype-graphql. - GraphQL Nexus — a code-first library without decorators, uses method chaining.
- Pothos GraphQL — a modern code-first library with excellent TypeScript support.
Advanced TypeGraphQL Features
Arguments and Mutations
import { Arg, Mutation } from "type-graphql";
@Resolver()class UserResolver { @Mutation(() => User) createUser(@Arg("name") name: string, @Arg("email") email: string): User { return { id: 3, name, email }; }}Validation with class-validator
import { Length, IsEmail } from "class-validator";import { InputType, Field } from "type-graphql";
@InputType()class CreateUserInput { @Field() @Length(2, 30) name: string;
@Field() @IsEmail() email: string;}Authorization via Middleware
import { UseMiddleware } from "type-graphql";
function AuthMiddleware(): MiddlewareFn { return async ({ context }, next) => { if (!context.user) throw new Error("Not authorized"); return next(); };}
@Resolver()class UserResolver { @Query(() => User) @UseMiddleware(AuthMiddleware) me(): User { return { id: 1, name: "Current user", email: "user@example.com" }; }}Integration with
Also in library
Working with XML in PHP: A Complete Guide to Parsing and Creating XML Documents
ASIO for C++: Complete Guide with Examples
JSON Processing in Node.js: A Complete Guide
PDF Generation in Java: Overview of the Best Libraries (iText, Apache PDFBox, OpenPDF)