-
Notifications
You must be signed in to change notification settings - Fork 9
/
repo.js
86 lines (73 loc) · 1.71 KB
/
repo.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
'use strict';
const crypto = require('crypto');
/* Repo is an abstract class
*
*
*/
class Repo{
initialize(){
return Promise.resolve();
}
/*
* - normalizedReq, Array
* - sign, String
* - options, Object, this is options for one request
* - options, Object, this is options for all requests
* - callback, Function
*
* Priority of two options : normalizedReq.options > options
*/
exists(normalizedReq, options){
const req = normalizedReq;
const slots = {};
const uniq = [];
const keysToInsert = {};
const rst = new Array(req.length);
for (let i = 0; i < req.length; i++) {
const reqOptions = Object.assign({},options,req[i].options);
const key = this.transformKey(req[i].sign);
if (key in slots) {
rst[i] = true;
} else {
rst[i] = false;
slots[key] = i;
uniq.push(key);
keysToInsert[key] = null;
if (reqOptions.rupdate === false) {
delete keysToInsert[key];
}
}
}
return this.getByKeys(uniq).then( (result) => {
const ifTruthy = (key) => key==='1' || key===1 || key==='true' || key===true ;
for (let j = 0; j < uniq.length; j++) {
if (ifTruthy(result[j])) {
rst[slots[uniq[j]]] = true;
delete keysToInsert[uniq[j]];
} else {
rst[slots[uniq[j]]] = false;
}
}
return this.setByKeys(Object.keys(keysToInsert));
}).then( () => {
return rst;
});
}
/*
*
* @return Array, transformed keys
*
*/
transformKey(key){
const hash = (str) => {
const hashFn = crypto.createHash('md5');
hashFn.update(str);
return hashFn.digest('hex');
};
return hash(key);
}
dispose(){
throw new Error('`dispose` not implemented');
}
}
module.exports = Repo;