Files
graphql-api-js/src/index.ts
T

86 lines
2.4 KiB
TypeScript

const newrelic = require('newrelic');
const newRelicPlugin = require('@newrelic/apollo-server-plugin');
import dotenv from 'dotenv';
dotenv.config();
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import resolvers from './resolvers';
import { readFileSync } from 'fs';
import { ContextValue } from './context';
import { GraphQLFormattedError } from 'graphql';
import express from 'express';
import http from 'http';
import cors from 'cors';
import { json } from 'body-parser';
import { getClientAccessToken } from './rest/cognitoService';
const path = require('path');
const typeDefs = readFileSync(
path.join(__dirname, './schema.graphql'),
).toString('utf-8');
async function main() {
try {
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer<ContextValue>({
typeDefs,
resolvers,
plugins: [
newRelicPlugin,
ApolloServerPluginDrainHttpServer({ httpServer }),
],
formatError: (formattedError: GraphQLFormattedError, error: unknown) => {
console.error(error);
newrelic.noticeError(error);
return formattedError;
},
});
await server.start();
app.get('/health', (req, res) => {
res.status(200).send('OK');
});
app.post('/login', async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
try {
const response = await getClientAccessToken(req);
res.status(200).send(response);
} catch (e) {
newrelic.noticeError(e.message);
res.status(401).send(e.message);
}
});
app.use(
'/',
cors<cors.CorsRequest>('*'),
json(),
expressMiddleware(server, {
context: async ({ req }) => {
const instance = new ContextValue({ req, server });
const context = await instance.process();
return context;
},
}),
);
await new Promise<void>((resolve) =>
httpServer.listen({ port: 4000 }, resolve),
);
console.log('SERVER IS RUNNING');
console.log(`ENV: ${process.env.ENVIRONMENT_NAME}`);
} catch (ex) {
newrelic.noticeError(ex);
console.error('Got terminal exception:', ex);
}
}
main();