-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
76 lines (64 loc) · 1.76 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
const express = require("express");
const mongoose = require("mongoose");
// require("dotenv").config({ path: "variables.env" });
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const Recipe = require("./models/Recipe");
const User = require("./models/User");
//Bring in GraphQL middleware
const { graphiqlExpress, graphqlExpress } = require("apollo-server-express");
const { makeExecutableSchema } = require("graphql-tools");
const { typeDefs } = require("./schema");
const { resolvers } = require("./resolvers");
//Create GraphQL Schema
const schema = makeExecutableSchema({
typeDefs: typeDefs,
resolvers: resolvers
});
//MIDDLEWARE IN USE
const app = express();
const corsOptions = {
origin: "http://localhost:3000",
credentials: true
};
app.use(cors(corsOptions));
//Set uop JWT authentication middleware
app.use(async (req, res, next) => {
const token = req.headers["authorization"];
if (token !== "null") {
try {
const currentUser = await jwt.verify(token, process.env.SECRET);
req.currentUser = currentUser;
} catch (error) {
console.log("Token not found");
}
}
next();
});
//Create GraphQL application
app.use("/graphiql", graphiqlExpress({ endpointURL: "/graphql" }));
//Connect Schemas with graphQL
app.use(
"/graphql",
bodyParser.json(),
graphqlExpress(({ currentUser }) => ({
schema,
context: {
Recipe,
User,
currentUser
}
}))
);
//Connect to Database and start Server
const PORT = process.env.PORT || 5000;
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err))
.then(() =>
app.listen(PORT, () => {
console.log(`Server started on ${PORT}`);
})
);