-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.js
executable file
·101 lines (88 loc) · 2.13 KB
/
helpers.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
99
100
101
'use strict';
const Promise = require('bluebird');
const Redis = require('ioredis');
const redis = new Redis({
port: process.env.PORT_REDIS, // Redis port
host: process.env.HOST_REDIS, // Redis host
db: 0
});
exports.create = function(data) {
const key = data.key;
const name = data.name;
if(!key) {
console.log("Key not exists");
throw "Key not exists";
}
if(!name) {
console.log("Name not exists");
throw "Name not exists";
}
console.log('Init create Key');
return new Promise((resolve, reject) => {
redis.set(key, JSON.stringify({ name }))
.then((result) => {
console.log("Result from create ", result);
resolve(result);
})
.catch((err) => {
console.log("Error from create ", err);
reject(err);
});
});
};
exports.findOne = function(key) {
if(!key) {
console.log("Key not exists");
throw "Key not exists";
}
console.log('Init find Key');
return new Promise((resolve, reject) => {
redis.get(key)
.then((result) => {
result = JSON.parse(result);
console.log("Read ", result);
resolve(result);
})
.catch((err) => {
console.log("Error from read ", err);
reject(err);
});
});
};
exports.update = function(key, data) {
if(!key) {
console.log("Key not exists");
throw "Key not exists";
}
if (data.key) {
delete data.key;
}
return this.findOne(key)
.then((r) => {
let dataSet = Object.assign(data, r);
return redis.set(key, JSON.stringify(dataSet))
.tap((result) => {
console.log("Result from update ", result);
})
.catchThrow((err) => {
console.log("Error from update ", err);
});
});
};
exports.remove = function(key) {
if(!key) {
console.log("Key not exists");
throw "Key not exists";
}
return new Promise((resolve, reject) => {
redis.del(key)
.then((result) => {
console.log("Remove item: ", result);
resolve(result);
})
.catch((err) => {
console.log("Error from remove item ", err);
reject(err)
});
})
};