-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
103 lines (87 loc) · 2.53 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
91
92
93
94
95
96
97
98
99
100
101
102
103
// Bring in Express.
const express = require('express');
// Initializes app
const app = express();
const jwt = require('jsonwebtoken');
const cors = require('cors');
const path = require('path');
app.use(cors());
app.use(function(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Expose-Headers', 'Content-Length');
next();
});
// connect your backend to mlab
const mongoose = require('mongoose');
// const bodyParser = require('body-parser');
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
// Set up JWT authentication middleware
app.use(async (req, res, next) => {
const token = await req.headers['authorization'];
if (token !== 'null') {
try {
const currentUser = await jwt.verify(token, process.env.SECRET);
req.currentUser = currentUser;
} catch (err) {
console.error(err);
}
}
next();
});
// allows to use different variables
require('dotenv').config({ path: 'variables.env' });
const Video = require('./models/Video');
const User = require('./models/User');
const Quiz = require('./models/Quiz');
const Next = require('./models/Next');
const Journal = require('./models/Journal');
// GraphQL-Express middleware
const { graphiqlExpress, graphqlExpress } = require('apollo-server-express');
const { makeExecutableSchema } = require('graphql-tools');
const { typeDefs } = require('./schema');
const { resolvers } = require('./resolvers');
// Creates graphql schema
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
// Creates graphiql
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));
// Connects schemas
app.use(
'/graphql',
express.json(),
graphqlExpress(({ currentUser }) => ({
cors: false,
schema,
context: {
Video,
User,
Quiz,
Next,
Journal,
currentUser
}
}))
);
// api routes
app.use('/api', require('./api/index'));
app.use('/videos', require('./videos/index'));
app.use(express.static(path.join(__dirname, '..', 'public')));
// actually connects to the database
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log('DB connected'))
.catch(err => console.error(err));
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'));
});
}
// Set up server.
const PORT = process.env.PORT || 4444;
app.listen(PORT, () => {
console.log(`Server tuning in on PORT ${PORT}`);
});