-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.js
303 lines (287 loc) · 10.6 KB
/
redis.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
const moment = require('moment');
const Redis = require('redis');
const object = require('./object');
module.exports = (url, helloMessage, models, rollbar) => {
const redis = Redis.createClient(url);
redis.on('error', err => {
rollbar.error(`Redis error: ${err}`);
});
redis.on('end', () => {
console.log('Redis connection closed');
});
helloMessage &&
redis.on('connect', () => {
console.log('Connected to REDIS!');
});
const transformMembers = (model, members) =>
members.map(member => {
const tMember = { ...member };
const keys = Object.keys(tMember);
for (let k = 0; k < keys.length; k += 1) {
const field = models[model].tableAttributes[keys[k]];
if (field && field.type.constructor.key === 'DATE' && tMember[keys[k]]) {
tMember[keys[k]] = moment(tMember[keys[k]]).valueOf();
}
}
return tMember;
});
const filterMembers = (model, members, where) => {
if (!where || Object.keys(where).length === 0) {
return members;
}
const baseMembers = transformMembers(model, members);
const result = [];
for (let k = 0; k < baseMembers.length; k += 1) {
if (object.check(baseMembers[k], where)) {
result.push(members[k]);
}
}
return result;
};
// Returning null || [member {}]
redis.find = (eventId, model, where = null, ...include) =>
new Promise(resolve => {
const finishEvent = eventId == null;
eventId = eventId == null ? rollbar.startEvent() : eventId;
// This method is used by redis.delete
redis.smembers(model, async (error, members) => {
if (error || !members) {
rollbar
.error(
`REDIS Error getting users, options:\n ${JSON.stringify(where, null, 2)}`,
`\n\nError:${error}\n\nResult: ${members}`
)
.useEvent(eventId);
finishEvent && rollbar.finishEvent(eventId);
return resolve(null);
}
members = members.map(member => JSON.parse(member));
members = filterMembers(model, members, where);
if (!include || !include.length) {
finishEvent && rollbar.finishEvent(eventId);
return resolve(members);
}
let included = [];
for (let k = 0; k < include.length; k += 1) {
const currInclude = include[k].include || [];
included.push(redis.find(eventId, include[k].model, include[k].where, ...currInclude));
}
included = await Promise.all(included);
for (let n = 0; n < members.length; n += 1) {
const thisMember = members[n];
for (let k = 0; k < include.length; k += 1) {
members[n][include[k].model] = [];
const currModel = include[k].model;
if (!models[model].relations[currModel]) {
rollbar
.error(`REDIS: model "${model}" has no relations with model "${currModel}".`)
.useEvent(eventId);
continue;
}
if (!models[model].relations) {
rollbar.error(`REDIS: model "${model}" has no relations with any model !!`).useEvent(eventId);
continue;
}
const { thisKey, otherKey } = models[model].relations[currModel];
if (!thisKey || !otherKey) {
rollbar
.error(`REDIS: model "${model}" has no thisKey or otherKey for model "${currModel}".`)
.useEvent(eventId);
continue;
}
for (let m = 0; m < included.length; m += 1) {
const curIncluded = (included[m] || []).filter(
other => other[otherKey] === thisMember[thisKey]
);
members[n][include[m].model] = curIncluded;
}
}
}
members = members.filter(member => {
for (let k = 0; k < include.length; k += 1) {
if (models[model].relations[include[k].model].innerJoin === false) {
continue;
}
if (!member[include[k].model] || member[include[k].model].length === 0) {
return false;
}
}
return true;
});
if (finishEvent) {
rollbar.finishEvent(eventId);
}
return resolve(members);
});
});
// Returning true || false || null
redis.delete = (eventId, model, where = {}) =>
new Promise(async resolve => {
const finishEvent = eventId == null;
eventId = eventId == null ? rollbar.startEvent() : eventId;
let members = await redis.find(eventId, model, where);
if (!members) {
finishEvent && rollbar.finishEvent(eventId);
return resolve(null);
}
if (members.length === 0) {
finishEvent && rollbar.finishEvent(eventId);
return resolve(false);
}
members = members.map(member => JSON.stringify(member));
redis.srem(model, members, (error, response) => {
if (error) {
rollbar
.error(
`REDIS Error deleting users, options:\n ${JSON.stringify(where, null, 2)}`,
`\n\nError:${error}\n\nResponse: ${response}`
)
.useEvent(eventId);
finishEvent && rollbar.finishEvent(eventId);
return resolve(null);
}
finishEvent && rollbar.finishEvent(eventId);
resolve(true);
});
});
// Returning true || false
redis.create = (eventId, model, registers) =>
new Promise(resolve => {
const finishEvent = eventId == null;
eventId = eventId == null ? rollbar.startEvent() : eventId;
const regsToAdd = registers.map(Reg => {
const reg = { ...Reg };
const keys = Object.keys(reg);
const modelNames = Object.keys(models);
for (let k = 0; k < keys.length; k += 1) {
if (modelNames.includes(keys[k])) {
delete reg[keys[k]];
}
}
return JSON.stringify(reg);
});
redis.sadd(model, regsToAdd, (error, response) => {
if (error) {
rollbar
.error(
`REDIS Registers not saved, key "${model}": \nRegisters: ${JSON.stringify(
regsToAdd,
null,
2
)}\nReason: ${error}\nRedis result: ${response}`
)
.useEvent(eventId);
finishEvent && rollbar.finishEvent(eventId);
return resolve(false);
}
if (!response) {
rollbar
.info(
`REDIS Register already exists:\n${regsToAdd.map(reg =>
JSON.stringify(JSON.parse(reg), null, 2)
)}`
)
.useEvent(eventId);
if (finishEvent) {
rollbar.finishEvent(eventId);
}
return resolve(true);
}
finishEvent && rollbar.finishEvent(eventId);
rollbar
.info(`REDIS Created registers:\n${regsToAdd.map(reg => JSON.stringify(JSON.parse(reg), null, 2))}`)
.useEvent(eventId);
resolve(true);
});
});
// Returning null || { found: Number, updated: Number }
redis.update = (eventId, model, update, where) =>
new Promise(async resolve => {
const finishEvent = eventId == null;
eventId = eventId == null ? rollbar.startEvent() : eventId;
const members = await redis.find(eventId, model, where);
if (!(update instanceof Object)) {
rollbar.error(`REDIS Param update must be an object, model "${model}"\n\nUpdate:\n${update}`);
finishEvent && rollbar.finishEvent(eventId);
return resolve(null);
}
if (!members) {
rollbar.error(
`REDIS Error getting members for updating, model "${model}"\n\nWhere:\n${JSON.stringify(
where,
null,
2
)}`
);
finishEvent && rollbar.finishEvent(eventId);
return resolve(null);
}
if (members.length === 0) {
rollbar
.warn(
`REDIS Didn't found members for updating, model "${model}"\n\nWhere:\n${JSON.stringify(
where,
null,
2
)}`
)
.useEvent(eventId);
finishEvent && rollbar.finishEvent(eventId);
return resolve(0);
}
const updateKeys = Object.keys(update);
let updated = 0;
for (let k = 0; k < members.length; k += 1) {
const oldMember = { ...members[k] };
for (let m = 0; m < updateKeys.length; m += 1) {
const field = updateKeys[m];
if (update[field] instanceof Object) {
if (update[field].$sumDate) {
const { unit } = update[field].$sumDate;
let { date, number } = update[field].$sumDate;
date = typeof date === 'string' ? moment(oldMember[date]) : date; // Parsing for cols
number = typeof number === 'string' ? oldMember[number] : number; // Parsing for cols
members[k][field] = date.add(number, `${unit}s`);
}
if (update[field].$sum) {
let { $sum: sum } = update[field];
sum = typeof sum === 'string' ? oldMember[sum] : sum;
members[k][field] += sum;
}
if (update[field].$subtract) {
let { $subtract: subtract } = update[field];
subtract = typeof subtract === 'string' ? oldMember[subtract] : subtract;
members[k][field] -= subtract;
}
continue;
}
members[k][field] = update[field];
}
updated += 1;
}
if (updated < members.length) {
rollbar
.warn(`REDIS Only will try to update ${updated} of ${members.length} members`)
.useEvent(eventId);
}
const deleted = await redis.delete(eventId, model, where); // Must be sequential
const created = await redis.create(eventId, model, members); // Must be sequential
if (!deleted && !created) {
rollbar.warn(`REDIS Update failed`).useEvent(eventId);
finishEvent && rollbar.finishEvent(eventId);
return resolve(null);
}
if (!deleted) {
rollbar.warn(`REDIS Old members not deleted !! Please delete old documents`).useEvent(eventId);
}
if (!created) {
rollbar.warn(`REDIS New members not created !! The old members are deleted ok`).useEvent(eventId);
finishEvent && rollbar.finishEvent(eventId);
return resolve(null);
}
rollbar.info(`Updated ${updated} / ${members.length} rows`).useEvent(eventId);
finishEvent && rollbar.finishEvent(eventId);
resolve({ found: members.length, updated });
});
return redis;
};