TypeScript & GraphQL
In this tutorial, we will explore how to create a GraphQL API using TypeScript. We will cover the basic concepts of GraphQL and demonstrate how to use TypeScript to create a strongly typed and maintainable server-side application.
Introduction to GraphQL
GraphQL is a query language for your API and a runtime for executing those queries against your data. It provides a more efficient, powerful, and flexible alternative to the traditional REST API. GraphQL allows clients to request only the data they need, making it a perfect fit for modern, data-driven applications.
Setting Up the Project
To start, we will create a new TypeScript project and install the necessary dependencies.
mkdir typescript-graphql
cd typescript-graphql
npm init -y
npm install typescript ts-node @types/node --save-dev
npm install express apollo-server-express graphql type-graphql --save
Create a tsconfig.json
file to configure TypeScript:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Creating a GraphQL Schema
In this step, we will create a simple GraphQL schema using the type-graphql
library. Create a new folder named src
and a file named schema.ts
inside it.
// src/schema.ts
import { ObjectType, Field, ID, Int, Resolver, Query } from 'type-graphql';
@ObjectType()
class Movie {
@Field(() => ID)
id: string;
@Field()
title: string;
@Field(() => Int)
year: number;
}
@Resolver()
class MovieResolver {
private movies: Movie[] = [
{ id: '1', title: 'Inception', year: 2010 },
{ id: '2', title: 'The Matrix', year: 1999 },
];
@Query(() => [Movie])
movies(): Movie[] {
return this.movies;
}
}
export { MovieResolver };
Setting Up the Server
Create a file named server.ts
inside the src
folder.
// src/server.ts
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import { buildSchema } from 'type-graphql';
import { MovieResolver } from './schema';
async function main() {
const app = express();
const schema = await buildSchema({
resolvers: [MovieResolver],
});
const server = new ApolloServer({ schema });
server.applyMiddleware({ app });
app.listen(4000, () => {
console.log(`Server running at http://localhost:4000${server.graphqlPath}`);
});
}
main();
Running the Server
Add the following script to your package.json
file:
"scripts": {
"start": "ts-node src/server.ts"
}
Run the server using the following command:
npm start
Visit http://localhost:4000/graphql
Querying the GraphQL API
Now that our server is running, we can use GraphQL Playground to interact with the API. Open your browser and visit http://localhost:4000/graphql
. In the left pane, you can write queries to fetch data. Try the following query:
query {
movies {
id
title
year
}
}
Press the "Play" button to execute the query. The right pane will display the results, which should look like this:
{
"data": {
"movies": [
{
"id": "1",
"title": "Inception",
"year": 2010
},
{
"id": "2",
"title": "The Matrix",
"year": 1999
}
]
}
}
Conclusion
In this tutorial, we covered the basics of creating a TypeScript-based GraphQL API. We introduced the type-graphql
library, which allows us to define GraphQL schemas in a strongly typed and maintainable way. We also demonstrated how to set up an Express server and use the Apollo Server middleware to serve the GraphQL API.
As you continue exploring TypeScript and GraphQL, consider learning more about mutations, subscriptions, and advanced schema concepts like input types, interfaces, and unions.