-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
59 lines (48 loc) · 1.72 KB
/
server.js
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
const express = require("express");
const jsonServer = require("json-server");
const chokidar = require("chokidar");
const cors = require("cors");
const fs = require("fs");
const { buildSchema } = require("graphql");
const { graphqlHTTP } = require("express-graphql");
const history = require("connect-history-api-fallback");
const queryResolvers = require("./serverQueriesResolver");
const mutationResolvers = require("./serverMutationsResolver");
const fileName = process.argv[2] || "./data.js";
const port = process.argv[3] || 3500;
const auth = require("./authMiddleware");
let router = undefined;
let graph = undefined;
const app = express();
const createServer = () => {
delete require.cache[require.resolve(fileName)];
setTimeout(() => {
router = jsonServer.router(
fileName.endsWith(".js") ? require(fileName)() : fileName
);
let schema =
fs.readFileSync("./serverQueriesSchema.graphql", "utf-8") +
fs.readFileSync("./serverMutationsSchema.graphql", "utf-8");
let resolvers = { ...queryResolvers, ...mutationResolvers };
graph = graphqlHTTP({
schema: buildSchema(schema),
rootValue: resolvers,
graphiql: true,
context: { db: router.db },
});
}, 100);
};
createServer();
app.use(history());
app.use("/", express.static("./build"));
app.use(cors());
app.use(jsonServer.bodyParser);
app.use(auth);
app.use("/api", (req, resp, next) => router(req, resp, next));
app.use("/graphql", (req, resp, next) => graph(req, resp, next));
chokidar.watch(fileName).on("change", () => {
console.log("Reloading web service data....");
createServer();
console.log("Reloading web service data complete.");
});
app.listen(port, () => console.log(`Web server running on port ${port}`));