-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
86 lines (68 loc) · 1.92 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { ApolloServer } from "apollo-server-express";
import {
ApolloServerPluginLandingPageGraphQLPlayground,
ApolloServerPluginDrainHttpServer,
ApolloServerPluginLandingPageDisabled,
} from "apollo-server-core";
import typeDefs from "./schemaGql.js";
import jwt from "jsonwebtoken";
import mongoose from "mongoose";
import dotenv from "dotenv";
import express from "express";
import http from "http";
import path from "path";
const __dirname = path.resolve();
const port = process.env.PORT || 4000;
const app = express();
const httpServer = http.createServer(app);
if (process.env.NODE_ENV !== "production") {
dotenv.config();
}
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on("connected", () => {
console.log("connected to mongodb");
});
mongoose.connection.on("error", (err) => {
console.log("err connecting", err);
});
//import models here
import "./models/Quotes.js";
import "./models/User.js";
import resolvers from "./resolvers.js";
// this is middle ware
const context = ({ req }) => {
const { authorization } = req.headers;
if (authorization) {
const { userId } = jwt.verify(authorization, process.env.JWT_SECRET);
return { userId };
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
context,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
process.env.NODE_ENV !== "production"
? ApolloServerPluginLandingPageGraphQLPlayground()
: ApolloServerPluginLandingPageDisabled(),
],
});
//api creation
if (process.env.NODE_ENV == "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
await server.start();
server.applyMiddleware({
app,
path: "/graphql",
});
httpServer.listen({ port }, () => {
console.log(`Server ready at port ${port} ${server.graphqlPath}`);
});