This repository has been archived by the owner on Dec 3, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepository.js
72 lines (65 loc) · 1.57 KB
/
repository.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
'use strict'
var _ = require('lodash')
var Promise = require('bluebird')
/**
* @param {redis} redis
* @param {String} prefix
* @constructor
*/
var Repository = function (redis, prefix) {
this.redis = redis
this.prefix = _.trim(prefix, ':') + ':'
}
/**
* @param {String} id
* @param {String} data
* @return {promise}
*/
Repository.prototype.store = function (id, data) {
var self = this
return Promise.try(function () {
return self.redis.setAsync(self.prefix + id, JSON.stringify(data))
})
}
/**
* @param {String} id
* @return {promise}
*/
Repository.prototype.fetch = function (id) {
var self = this
return Promise.try(function () {
return self.redis.getAsync(self.prefix + id)
}).then(function (data) {
return JSON.parse(data)
})
}
function scan (redis, prefix, cursor) {
return redis.scanAsync(cursor, 'MATCH', prefix + '*', 'COUNT', '100')
}
/**
* @return {promise}
*/
Repository.prototype.list = function () {
var self = this
return Promise.try(function () {
var cursor = '0'
var keys = []
var scanFunc = scan.bind(scan, self.redis, self.prefix)
return scanFunc(cursor)
.then(function (result) {
cursor = result[0]
keys = keys.concat(result[1])
if (cursor === '0') {
return keys
}
return scanFunc(cursor).then(this)
})
}).then(function (keys) {
return Promise.map(keys, function (key) {
return self.redis.getAsync(key).then(function (data) {
return [_.trimLeft(key, self.prefix), JSON.parse(data)]
})
})
})
}
module.exports = Repository