-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
133 lines (114 loc) · 2.54 KB
/
index.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
/**
* Module dependencies
*/
var Request = require('hyper-path');
var Emitter = require('component-emitter');
var debug = require('debug')('hyper-map');
/**
* Expose the HyperMap
*/
module.exports = HyperMap;
/**
* Create a HyperMap Client
*
* @param {Object?} resources
* @param {Object?} errors
*/
function HyperMap(resources, errors) {
this._resources = resources || {};
this._errors = errors || {};
this._completed = {};
this.size = 0;
for (var r in resources) {
if (!resources.hasOwnProperty(r)) continue;
this._completed[r] = true;
this.size++;
}
}
Emitter(HyperMap.prototype);
/**
* Lookup a resource with the path and scope
*
* @param {String} path
* @param {Object?} scope
* @param {String?} delim
* @return {Object}
* @api public
*/
HyperMap.prototype.get = function(path, scope, delim) {
var self = this;
var client = createClient(self);
var req = new Request(path, client, delim);
req.scope(scope || {});
return req.get(function(err, value) {
if (err) throw err;
return {
completed: client.completed,
value: value,
request: req
};
});
};
/**
* Set the value of a resource
*
* @param {String} href
* @param {Object} value
* @return {HyperMap}
* @api public
*/
HyperMap.prototype.set = function(href, value) {
this._resources[href] = value;
if (!this._completed[href]) this.size++;
this._completed[href] = true;
return this;
};
/**
* Set the error response for a resource
*
* @param {String} href
* @param {Error} err
* @return {HyperMap}
* @api public
*/
HyperMap.prototype.error = function(href, err) {
this._errors[href] = err;
if (!this._completed[href]) this.size++;
this._completed[href] = true;
return this;
};
/**
* Remove a resource from the store
*
* @param {String} href
* @return {HyperMap}
* @api public
*/
HyperMap.prototype.delete = function(href) {
if (this._completed[href]) this.size--;
delete this._resources[href];
delete this._completed[href];
delete this._errors[href];
return this;
};
function createClient(map) {
var client = {
completed: true,
requests: []
};
client.root = root;
client.get = get;
return client;
function root(cb) {
return get('.', cb);
}
function get(href, cb) {
map.emit('request', href);
client.requests.push(href);
client.completed = client.completed && !!map._completed[href];
var err = map._errors[href] || void 0;
var val = map._resources[href];
debug('fetching cache for ' + href, err, val);
return cb(err, val, null, null, false);
}
}