-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (70 loc) · 2.13 KB
/
index.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import path from "path";
import "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import typeDefs from "./graphql/schema.js";
import resolvers from "./graphql/resolvers.js";
import auth from "./middlewares/auth.js";
import { createServer } from "http";
import { execute, subscribe } from "graphql";
import { SubscriptionServer } from "subscriptions-transport-ws";
import { makeExecutableSchema } from "@graphql-tools/schema";
import { ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";
import { ApolloServer } from "apollo-server-express";
import { graphqlUploadExpress } from "graphql-upload";
const MONGO_URI =
process.env.NODE_ENV === "production"
? process.env.MONGO_URI
: "mongodb://localhost/graphql";
try {
await mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
console.log("Database connection successful !!!");
} catch (error) {
console.log(error);
}
const app = express();
const httpServer = createServer(app);
const __dirname = path.resolve();
const schema = makeExecutableSchema({ typeDefs, resolvers });
const server = new ApolloServer({
schema,
formatError: (err) => {
const code = err.originalError.code || 500;
return { code, ...err };
},
context: ({ req, res }) => ({ req }),
introspection: true,
plugins: [ApolloServerPluginLandingPageGraphQLPlayground()],
});
await server.start();
app.use(auth);
app.use("/images", express.static(path.join(__dirname, "images")));
app.use(graphqlUploadExpress());
server.applyMiddleware({ app });
const subscriptionServer = SubscriptionServer.create(
{
schema,
execute,
subscribe,
},
{
server: httpServer,
path: server.graphqlPath,
}
);
["SIGINT", "SIGTERM"].forEach((signal) => {
process.on(signal, () => {
subscriptionServer.close();
httpServer.close(() => {
process.exit(0);
});
});
});
httpServer.listen(process.env.PORT, () => {
console.log(`http://localhost:${process.env.PORT}`);
});