Starter template for use graphql-yoga with express(typescript)
Mehedi Hasan
Posted on November 4, 2024
Here’s a starter template to set up a TypeScript project using express with graphql-yoga for a GraphQL server.
Steps
- Initialize the Project: First, set up a new Node.js project.
mkdir graphql-yoga-express && cd graphql-yoga-express
npm init -y
- Install Dependencies: Install the required packages.
npm install express graphql graphql-yoga
npm install -D typescript ts-node @types/express @types/node
- Set Up TypeScript: Initialize TypeScript configuration.
npx tsc --init
Adjust your tsconfig.json (optional but recommended changes):
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
- Project Structure: Create the following project structure.
graphql-yoga-express
├── src
│ ├── index.ts # Entry point of the server
│ ├── schema.ts # Define GraphQL schema and resolvers
├── package.json
├── tsconfig.json
- Create GraphQL Schema and Resolvers: Inside src/schema.ts, define a basic schema and resolver.
// src/schema.ts
import { createSchema } from 'graphql-yoga';
const typeDefs = /* GraphQL */ `
type Query {
hello(name: String): String!
}
`;
const resolvers = {
Query: {
hello: (_: unknown, { name }: { name: string }) => `Hello, ${name || 'World'}!`,
},
};
export const schema = createSchema({
typeDefs,
resolvers,
});
- Set Up the Server with Express: Inside src/index.ts, create an Express server and use graphql-yoga middleware.
// src/index.ts
import express from 'express';
import { createYoga } from 'graphql-yoga';
import { schema } from './schema';
const app = express();
const yoga = createYoga({ schema });
app.use('/graphql', yoga);
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}/graphql`);
});
- Run the Server: Add a script to package.json for running the server in development mode.
"scripts": {
"start": "ts-node src/index.ts"
}
Then, start the server:
npm start
Test the GraphQL Endpoint
Open http://localhost:4000/graphql in your browser, and test the query:
query {
hello(name: "GraphQL-Yoga")
}
You should receive a response like:
{
"data": {
"hello": "Hello, GraphQL-Yoga!"
}
}
This setup provides a basic Express server with graphql-yoga as the GraphQL layer. You can expand the schema and resolvers as needed.
💖 💪 🙅 🚩
Mehedi Hasan
Posted on November 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.