forked from jsprieto10/recetaspatodos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
98 lines (85 loc) · 2.2 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
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var api = express();
app.use("/api", api);
api.use(bodyParser.urlencoded({ extended: false }));
api.use(bodyParser.json());
const creds = require("./credential.json");
const MongoClient = require("mongodb").MongoClient;
const url =
"mongodb://" +
creds.user +
":" +
creds.pass +
"@ds0" +
creds.port +
".mlab.com:" +
creds.port +
"/" +
creds.db;
const path = require("path");
app.use(express.static(path.join(__dirname, "front-end/build")));
console.log(url);
function findRecetas(db, callback, ingredientes) {
const c = db.collection("RecetasPaTodos");
if (ingredientes.length) {
c.find({ ingredientes: { $all: ingredientes } }).toArray((err, docs) => {
if (err) throw err;
callback(docs);
});
} else {
c.find().toArray((err, docs) => {
if (err) throw err;
callback(docs);
});
}
}
function getRecetas(callback, ingredientes) {
MongoClient.connect(url, (err, client) => {
if (err) throw err;
console.log("Connected successfully to server");
const db = client.db("webdev");
findRecetas(db, callback, ingredientes);
client.close();
});
}
function postReceta(db, callback, receta) {
const col = db.collection("RecetasPaTodos");
col.save(receta, (err, r) => {
if (err) throw err;
console.log(r);
callback(receta);
});
}
function postRe(callback, receta) {
MongoClient.connect(url, (err, client) => {
if (err) throw err;
console.log("Connected successfully to server");
const db = client.db("webdev");
postReceta(db, callback, receta);
client.close();
});
}
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/front-end/build/index.html"));
});
api.post("/getData", function(req, res) {
console.log("getData");
getRecetas(function(tweets) {
res.send(tweets);
}, req.body.ingredientes);
});
api.post("/postReceta", (req, res) => {
console.log("entro");
postRe(r => res.send(r), req.body);
});
api.get("/", function(req, res) {
console.log("api general");
getRecetas(function(tweets) {
res.send(tweets);
}, []);
});
app.listen(3001, () => {
console.log("Listening on:3001");
});