Skip to content

Instantly share code, notes, and snippets.

@pontusab
Created April 3, 2019 17:55
Show Gist options
  • Save pontusab/17669973d098b072e7d1ef4fe3a3ed2c to your computer and use it in GitHub Desktop.
Save pontusab/17669973d098b072e7d1ef4fe3a3ed2c to your computer and use it in GitHub Desktop.
// NOTE: Required for reuse of connection
import './utils/typeorm-monkeypatch'
import * as express from 'express'
import { ApolloServer } from 'apollo-server-express'
import { getConnectionManager, Connection } from 'typeorm'
import { PostgresDriver } from 'typeorm/driver/postgres/PostgresDriver'
import * as depthLimit from 'graphql-depth-limit'
import formatError from './utils/formatError'
import schema from './schema'
import { options} from './models'
const debug = require('debug')('api:server')
const { PORT = 4000 } = process.env
const manager = getConnectionManager()
let connection: Connection
async function server() {
if (manager.has('default')) {
connection = await manager.get('default')
debug('Reusing existing connection from manager.')
} else {
debug('Creating new connection to DB.')
connection = await manager.create(options)
}
if (!connection.isConnected) {
debug('Cached connection was not connected, attempting to reconnect.')
await connection.connect()
}
const server = new ApolloServer({
formatError,
schema,
validationRules: [depthLimit(10)],
})
const app = express()
server.applyMiddleware({ app })
app.listen({ port: PORT }, () => {
debug(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
})
}
server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment