-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
67 lines (59 loc) · 2.39 KB
/
main.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
const express = require("express");
const bodyParser = require("body-parser");
const mongo = require("mongodb");
const client = require('mongodb').MongoClient;
const app = express();
const omdbapi = require('./functions/omdbApi.js');
const movies = require('./functions/listMovies.js');
const url =
"mongodb+srv://nativapps_test:[email protected]/<OMDb-Movies>?retryWrites=true&w=majority";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', "*")
res.removeHeader('X-Powered-By')
res.header('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept, Authorization")
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
next()
});
app.get("/get_movies", async (req, res, next) => {
await client.connect(url, async (err, db) => {
if (err) {
res.status(401).json({
status: "Fail",
message: 'No tiene autorización a la base de datos.'
});
next();
} else {
let bd = db.db("OMDb-Movies");
//Consulto si existe la colección, para no insertar data duplicada.
bd.listCollections({ "name": "movielist_202102071230jramos" }).next(async (err, coll) => {
if (coll) {
//Si existe la colección, solo busco los datos;
let document = await movies.getMovies(bd);
res.status(200).json({
status: 'Ok',
document: document,
count: document.length
});
next();
} else {
//Si no existe la colección inserto los datos.
let status = await omdbapi.insertMovies(bd);
if (status) {
let document = await movies.getMovies(bd);
res.status(200).json({
status: 'Ok',
document: document,
count: document.length
});
next();
}
}
})
}
})
});
app.listen(process.env.PORT || 3000, () => {
console.log(' API is listening on port ', process.env.PORT || 3000)
})