-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
63 lines (56 loc) · 1.6 KB
/
Copy pathserver.js
File metadata and controls
63 lines (56 loc) · 1.6 KB
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
const { ApolloServer, AuthenticationError } = require("apollo-server");
const mongoose = require("mongoose");
const fs = require("fs");
const path = require("path");
const jwt = require("jsonwebtoken");
require("dotenv").config({ path: "variables.env" });
const resolvers = require("./resolvers");
const User = require("./models/User");
const Post = require("./models/Post");
// Obtener la ruta absoluta del archivo typeDefs
const filePath = path.join(__dirname, "typeDefs.gql");
const typeDefs = fs.readFileSync(filePath, "utf-8");
// Conexión con la base de datos mlab
mongoose
.connect(
process.env.MONGO_URI,
{ useNewUrlParser: true }
)
.then(() => {
console.log("BD conectada");
})
.catch(error => {
console.log(error);
});
// Verificar el token generado con jwt obtenido del cliente
const getUser = async token => {
if (token) {
try {
return await jwt.verify(token, process.env.SECRET);
} catch (error) {
throw new AuthenticationError(
"Tu sesión ha expirado. Ingresa nuevamente"
);
}
}
};
// Crear servidor Apollo/GraphQl usando typedefs, resolvers y context
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: error => {
return {
name: error.name,
message: error.message
};
},
context: async ({ req }) => {
// Obtener el token
const token = req.headers["authorization"];
return { User, Post, currentUser: await getUser(token) };
}
});
//{ port: process.env.PORT || 4000 }
server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
console.log("Server is running " + url);
});