-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
90 lines (78 loc) · 2.24 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
87
88
89
90
import {
ApolloServerPluginLandingPageGraphQLPlayground,
ApolloServerPluginDrainHttpServer,
ApolloServerPluginLandingPageDisabled,
} from 'apollo-server-core';
import { ApolloServer } from 'apollo-server-express';
import typeDefs from './schema.js';
import mongoose from 'mongoose';
import jwt from 'jsonwebtoken';
import express from 'express';
import dotenv from 'dotenv';
import http from 'http';
import path from 'path';
import cors from 'cors';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Read the .env file
if (process.env.NODE_ENV !== 'production') {
dotenv.config();
}
// Port
const port = process.env.PORT || 5000;
// Connect to MongoDB
mongoose
.connect(process.env.MONGO_DB_URL)
.then(() => {
console.log('MongoDB connected successfully !!');
})
.catch((err) => {
console.log(err);
});
// Import Models
import './models/User.js';
import './models/Quote.js';
// Import the resolvers
import resolvers from './resolver.js';
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const { authorization } = req.headers || {};
// Check if authorization header is present
if (authorization) {
// Verify the token
const { userID } = jwt.verify(
authorization,
process.env.JWT_SECRET_KEY
);
return { userID };
}
},
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
process.env.NODE_ENV !== 'production'
? ApolloServerPluginLandingPageGraphQLPlayground()
: ApolloServerPluginLandingPageDisabled(),
],
});
// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client', 'build')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
// CORS
app.use(cors({ origin: process.env.CLIENT_URL, credentials: true }));
app.use(express.json()); // tell the server to accept the json data from frontend
await server.start();
server.applyMiddleware({ app, path: '/graphql' });
httpServer.listen({ port }, () => {
console.log(
`🚀 Server ready at http://localhost:4000${server.graphqlPath}`
);
});