graphql in typescript

To use GraphQL in a TypeScript project, you will need to install some dependencies. Here are the steps you need to follow:

  1. Install graphql and apollo-server packages via npm:
index.ts
npm install graphql apollo-server
34 chars
2 lines
  1. Create a schema using the buildSchema function provided by the graphql package:
index.ts
import { buildSchema } from 'graphql';

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);
110 chars
8 lines
  1. Create a resolver function for the hello field:
index.ts
const rootResolver = {
  hello: () => {
    return 'Hello world!';
  }
};
74 chars
6 lines
  1. Initialize the Apollo server with the schema and resolver:
index.ts
import { ApolloServer } from 'apollo-server';

const server = new ApolloServer({
  schema,
  rootResolver
});

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
192 chars
11 lines
  1. Finally, start the server by running the following command:
index.ts
node index.js
14 chars
2 lines

This is just a basic example of how to use GraphQL with TypeScript. There are many other libraries and tools that can help you build robust and scalable GraphQL server such as TypeGraphQL, graphql-tools, and Prisma client.

gistlibby LogSnag