← Back
apollo gist graphql typescript

Typescript apollo server setup

Project setup #

mkdir server
echo '{ "private": true }' > package.json
echo 'node_modules' > .gitignore
git init
npm i typescript nodemon ts-node --save-dev
npx tsc --init --rootDir src --outDir build --lib dom,es6 --module commonjs --removeComments
mkdir src
touch src/server.ts

package.json:

{
"scripts": {
"dev": "nodemon 'src/server.ts' --exec 'ts-node' src/server.ts -e ts,graphql"
}
}

Add Apollo server #

npm i apollo-server apollo-server-express compression cors express graphql http ncp
npm i graphql-type-json graphql-iso-date lodash
npm i --save-dev @types/compression @types/express @types/graphql @types/graphql-depth-limit @types/node
npm i --save-dev graphql-depth-limit graphql-import graphql-import-node

server.ts:

import express from "express";
import { ApolloServer } from "apollo-server-express";
import depthLimit from "graphql-depth-limit";
import { createServer } from "http";
import compression from "compression";
import cors from "cors";
import schema from "./graphql/schema";

const PORT = process.env["PORT"] || 3000;
const app = express();

const server = new ApolloServer({
...schema,
validationRules: [depthLimit(7)],
});

app.use("*", cors());
app.use(compression());
server.applyMiddleware({ app, path: "/graphql" });

const httpServer = createServer(app);
httpServer.listen({ port: PORT }, (): void => {
console.log(`GraphQL server ready http://localhost:${PORT}/graphql`);
});

Add datasource #

npm i --save apollo-datasource isemail mime uuid
class UserDataSource extends DataSource {
constructor() {
super();
}
}