-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
65 lines (55 loc) · 1.59 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// tslint:disable:no-console
import "reflect-metadata";
import { ApolloServer } from "apollo-server-express";
import * as express from "express";
import { importSchema } from "graphql-import";
import { createConnection } from "typeorm";
import resolvers from "./be/resolvers";
import { setupNextJSApp } from "./fe";
import ormConfig from "./ormconfig";
interface ServerOptions {
backendOnly?: boolean; // Enable to test the graphql server only
database?: any; // Override the database to connect to (eg. for testing)
}
/**
* startServer
* Starts the express app that serves both the frontend and backend
*/
export async function startServer(options?: ServerOptions) {
const expressApp = express();
// Connect to DB
const db = await createConnection({
...ormConfig,
...{
database: options ? options.database : undefined
}
});
// Prepare ApolloServer
const apolloServer = new ApolloServer({
context: ({ req }) => ({
db,
req
}),
resolvers,
typeDefs: importSchema("./be/schema/schema.graphql")
});
apolloServer.applyMiddleware({ app: expressApp });
if (!options || !options.backendOnly) {
setupNextJSApp(expressApp);
}
// Start express server
const httpServer = expressApp.listen(process.env.PORT, () => {
// tslint:disable-next-line no-console
console.log(
`Server started, listening on port ${
process.env.PORT
} for incoming requests.`
);
});
// Close the db connection when server exits
httpServer.on("close", () => {
console.log("App shutting down...");
db.close();
});
return httpServer;
}