-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.js
96 lines (83 loc) · 2.47 KB
/
storage.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
const fs = require('fs');
const dbase = require('mongoose');
const Model = require('./model');
let settings = JSON.parse(fs.readFileSync('appsettings.json'));
// usar las promesas del scope global de forma nativa
dbase.Promise = global.Promise; // <= para implementar promesas con controladores *pendiente*
dbase.connect(settings["connectionStrings"]["mongoLocal"], { useNewUrlParser: true });
console.log("Base de datos conectada con exito");
function getAllClients() {
return new Promise(async(resolve, reject) => {
const result = await Model.find({}).lean().exec(function(e, d) {
if (e) {
reject(e);
}
resolve(d)
});
});
}
function addClient(client) {
return new Promise((resolve, reject) => {
const newClient = new Model(client);
const queryResult = newClient.save(function(err, data) {
if (err) {
reject(err);
}
resolve(client);
});
});
}
function getClientByPhoneNumber(phone) {
return new Promise((resolve, reject) => {
const result = Model.find({ "PhoneNumber": { $regex: '.*' + phone + '.*' } }, function(error, data) {
if (error) {
reject(error);
}
if (data.length > 1) {
resolve(data);
}
reject(data);
});
});
}
function getClientById(id) {
return new Promise((resolve, reject) => {
const result = Model.findById(id, function(error, data) {
if (error) {
console.log(error);
reject(error);
}
resolve(data)
});
});
}
function updateById(client) {
return new Promise((resolve, reject) => {
const clientRecord = Model.findByIdAndUpdate(client.id, client, function(err, data) {
if (err) {
reject(err);
}
resolve(data);
});
});
}
function deleteById(id) {
return new Promise((resolve, reject) => {
const result = Model.findByIdAndRemove(id, function(error, data) {
if (error) {
console.log(error);
reject(error);
}
resolve(data)
});
});
}
module.exports = {
addClient: addClient,
getAllClients: getAllClients,
getClientByPhoneNumber: getClientByPhoneNumber,
updateById: updateById,
getClientById: getClientById,
deleteById: deleteById,
dbase: dbase
}