-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
411 lines (337 loc) · 9.7 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
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
function noop() {}
/**
* Expose the Request object
*/
module.exports = Request;
/**
* Get a reference to hasOwnProperty
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Create a hyper-path request
*
* @param {String} path
* @param {Client} client
*/
function Request(path, client, delim) {
if (!(this instanceof Request)) return new Request(path, client);
// init client
this.client = client;
if (!this.client) throw new Error('hyper-path requires a client to be passed as the second argument');
this.delim = delim || '.';
this.parse(path);
this._listeners = {};
this._scope = {};
this._warnings = {};
}
/**
* Set the root scope
*
* @param {Object} scope
* @return {Request}
*/
Request.prototype.scope = function(scope) {
this._scope = this.wrappedScope ? [scope] : scope;
if (this._fn) this.get();
return this;
};
/**
* Call a function anytime the data changes in the request
*
* @param {Function} fn
* @return {Request}
*/
Request.prototype.on = function(fn) {
this._fn = fn;
this.get();
return this;
};
/**
* Refresh the data down the path
*
* @return {Request}
*/
Request.prototype.get =
Request.prototype.refresh = function(fn) {
var scope = this._scope;
fn = fn || this._fn;
// Clear any previous listeners
this.off();
return this.isRoot ?
this.fetchRoot(scope, fn) :
this.traverse(scope, {}, 0, this.path, {}, true, fn);
};
/**
* Issue a warning once per request
*
* @param {String} str
*/
Request.prototype.warn = function(str) {
if (this._warnings[str]) return;
console.warn(str);
this._warnings[str] = true;
return this;
};
/**
* Parse the string with the following syntax
*
* Start at this.scope['path']
*
* path.to.my.name
*
* Start at the client's root
*
* .path.to.my.name
*
* @param {String} str
* @api private
*/
Request.prototype.parse = function(str) {
var path = this.path = Array.isArray(str) ? str.slice() : str.split(this.delim);
this.index = path[0];
if (path.length === 1) {
this.wrappedScope = true;
path.unshift(0);
}
this.isRoot = this.index === '';
this.target = path[path.length - 1];
};
/**
* unsubscribe from any emitters for a request
*
* @return {Request}
*/
Request.prototype.off = function() {
for (var key in this._listeners) {
this.replaceListener(key, null, this._fn);
}
return this;
};
/**
* Traverse properties in the api
*
* @param {Any} parent
* @param {Object} links
* @param {Integer} i
* @param {Array} path
* @param {Object} parentDocument
* @param {Boolean} normalize
* @param {Function} cb
* @api private
*/
Request.prototype.traverse = function(parent, links, i, path, parentDocument, normalize, cb) {
var self = this;
// we're done searching
if (i >= path.length) return cb(null, normalize ? self._normalizeTarget(parent) : parent, parentDocument);
var key = path[i];
var value = self._get(key, parent, links);
// we couldn't find the property
if (!isDefined(value)) {
if (i !== 0 || !self._get('href', parent)) return self.handleUndefined(key, parent, links, i, path, parentDocument, normalize, cb);
// handle cases where the scope has an href
path = path.slice();
path.unshift('value');
return self.traverse({
value: parent
}, links, 0, path, parentDocument, normalize, cb);
}
var next = i + 1;
var nextProp = path[next];
var href = self._get('href', value);
// we don't have a link to use or it's set locally on the object
if (!href || hasOwnProperty.call(value, nextProp) || path.length === 1) return self.traverse(value, links, next, path, parentDocument, normalize, cb);
// fetch the resource
return self.fetchResource(href, next, path, normalize, cb);
};
/**
* Handle an undefined value
*
* @param {String} key
* @param {Object|Array} parent
* @param {Object} links
* @param {Integer} i
* @param {Array} path
* @param {Object} parentDocument
* @param {Boolean} normalize
* @param {Function} cb
*/
Request.prototype.handleUndefined = function(key, parent, links, i, path, parentDocument, normalize, cb) {
// check to make sure it's not on a "normalized" target
var coll = this._normalizeTarget(parent);
if (this._get(key, coll)) return this.traverse(coll, links, i, path, parentDocument, normalize, cb);
var value = parent && parent[key];
if (typeof value === 'function') return cb(null, value.bind(parent), parentDocument);
value = value || coll && coll[key];
if (typeof value === 'function') return cb(null, value.bind(coll), parentDocument);
return cb(null, value, parentDocument);
};
/**
* Fetch the root resource through the client
*
* @param {Object} scope
* @param {Function} cb
*/
Request.prototype.fetchRoot = function(scope, cb) {
var self = this;
var res = self.client.root(function handleRoot(err, body, links, href, shouldResolve) {
if (err) return cb(err);
if (!body && !links) return cb(null);
links = links || {};
var bodyHref = self._get('href', body);
href = href || bodyHref;
if (!href) self.warn('root missing href: local JSON pointers will not function properly');
else body = shouldResolve === false ?
body :
self._resolve(bodyHref, body);
return self.traverse(body || scope, links, 1, self.path, body, true, cb);
});
return self.replaceListener('.', res, cb);
};
/**
* Fetch a resource through the client
*
* @param {String} href
* @param {Integer} i
* @param {Array} path
* @param {Boolean} normalize
* @param {Function} cb
*/
Request.prototype.fetchResource = function(href, i, path, normalize, cb) {
var self = this;
var orig = href;
var parts = orig.split('#');
href = parts[0];
if (href === '') return cb(new Error('cannot request "' + orig + '" without parent document'));
var res = self.client.get(href, function handleResource(err, body, links, hrefOverride, shouldResolve) {
if (err) return cb(err);
if (!body && !links) return cb(null);
links = links || {};
// allow clients to override the href (usually because of a redirect)
href = hrefOverride || href;
// Be nice to APIs that don't set 'href'
var bodyHref = self._get('href', body);
if (!bodyHref) body = self._set('href', href, body);
var resolved = shouldResolve === false ?
body :
self._resolve(bodyHref || href, body);
return parts.length === 1 ?
self.traverse(resolved, links, i, path, resolved, normalize, cb) :
self.fetchJsonPath(href, resolved, links, parts[1], i, path, normalize, cb);
});
return self.replaceListener(orig, res, cb);
};
/**
* Replace the listener for a key
*
* @param {String} key
* @param {Any} res
* @param {Function} cb
* @return {Any}
*/
Request.prototype.replaceListener = function(key, res, cb) {
if (this._fn !== cb) return res;
(this._listeners[key] || noop)();
if (!res) delete this._listeners[key];
else this._listeners[key] = typeof res === 'function' ? res : noop;
return res;
};
/**
* Traverse a JSON path
*
* @param {String} parentHref
* @param {Object} parentDocument
* @param {Object} links
* @param {String} href
* @param {Integer} i
* @param {Array} path
* @param {Boolean} normalize
* @param {Function} cb
*/
Request.prototype.fetchJsonPath = function(parentHref, parentDocument, links, href, i, path, normalize, cb) {
var self = this;
var pointer = href.split('/');
var resolvedHref = (parentDocument.href || parentHref || '') + '#' + href;
if (pointer[0] === '') pointer.shift();
return self.traverse(parentDocument, links, 0, pointer, parentDocument, false, function handleJsonPath(err, val) {
if (err) return cb(err);
if (!self._get('href', val)) val = self._set('href', resolvedHref, val);
return self.traverse(val, links, i, path, parentDocument, normalize, cb);
});
};
/**
* Resolve any local JSON pointers
*
* @param {String} root
* @param {Any} body
* @return {Any}
*/
Request.prototype._resolve = function(root, body, type) {
if (!body || (type || typeof body) !== 'object') return body;
var obj = Array.isArray(body) ? [] : {};
var value, childType;
for (var key in body) {
if (!hasOwnProperty.call(body, key)) continue;
value = body[key];
childType = typeof value;
if (key === 'href' && childType === 'string' && value.charAt(0) === '#') {
obj.href = root + value;
} else {
obj[key] = this._resolve(root, value, childType);
}
}
return obj;
};
/**
* Get a value given a key/object
*
* @api private
*/
Request.prototype._get = function(key, parent, fallback) {
if (!parent) return void 0;
if (hasOwnProperty.call(parent, key)) return parent[key];
if (typeof parent.get === 'function') return parent.get(key);
if (fallback && hasOwnProperty.call(fallback, key)) return {href: fallback[key]};
return void 0;
}
/**
* Set a value on an object
*
* @api private
*/
Request.prototype._set = function(key, value, obj) {
if (!obj || typeof obj !== 'object') return obj;
if (typeof obj.set === 'function') return obj.set(key, value);
obj[key] = value;
return obj;
}
/**
* If the final object is an collection, pass that back
*
* @api private
*/
Request.prototype._normalizeTarget = function(target) {
if (typeof target !== 'object' || !target) return target;
var href = this._get('href', target);
target = firstDefined(this._get('collection', target), this._get('data', target), target);
return href ? this._set('href', href, target) : target;
}
/**
* Choose the first defined value
*
* @api private
*/
function firstDefined() {
for (var i = 0, l = arguments.length, v; i < l; i++) {
v = arguments[i];
if (typeof v !== 'undefined') return v;
}
return v;
}
/**
* Check if a value is defined
*
* @api private
*/
function isDefined(value) {
return typeof value !== 'undefined' && value !== null;
}