-
Notifications
You must be signed in to change notification settings - Fork 0
/
refs.js
100 lines (91 loc) · 2.18 KB
/
refs.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
/**
* Class with parse and get methods for multi-storage refs syntax.
*
* @namespace
* @param {Object.<string, *>} storages
* @param {Object.<string, Refs~getter>} getters
* @description `import { Refs } from 'ancient-refs';`
*/
var Refs = function(storages, getters) {
this.storages = storages;
this.getters = getters;
};
/**
* @memberof Refs
* @param {String} storage
* @param {String} id
* @return {String} ref
* @description `refs.generate('items', 'abc'); // 'items/abc'`
* @throws StorageName must be a string!
* @throws Id must be a string!
*/
Refs.prototype.generate = function(storageName, id) {
if (typeof(storageName) != 'string') {
throw new Error('StorageName must be a string!');
}
if (typeof(id) != 'string') {
throw new Error('Id must be a string!');
}
return storageName+'/'+id;
};
/**
* @memberof Refs
* @param {String} ref
* @return {String[]|undefined} [_ref]
* @description `refs.parse('items/abc'); // ['items','abc']`
*/
Refs.prototype.parse = function(id) {
if (typeof(id) != 'string') {
return undefined;
}
return id.split('/');
};
/**
* @memberof Refs
* @param {String} ref
* @param {Refs~callback} [callback]
* @return {Object|undefined} [document]
* @description `refs.get('items/abc'); // 123`
*/
Refs.prototype.get = function(ref, callback) {
var _ref = this.parse(ref);
if (!_ref) return undefined;
return this.getters[_ref[0]](_ref[1], callback);
};
/**
* @memberof Refs
* @param {String} ref
* @return {*} [storage]
*/
Refs.prototype.storage = function(ref) {
var _ref = this.parse(ref);
if (!_ref) return undefined;
return this.storages[_ref[0]];
};
Refs.prototype.collection = Refs.prototype.storage;
/**
* @memberof Refs
* @param {String} ref
* @return {String} id
*/
Refs.prototype.id = function(ref) {
var _ref = this.parse(ref);
if (!_ref) return undefined;
return _ref&&_ref[1]?_ref[1]:undefined;
};
/**
* Callback from get method.
*
* @callback Refs~callback
* @param {Error} [error]
* @param {*} [data]
*/
/**
* Adapter for get data from storage by id.
*
* @callback Refs~getter
* @param {String} id
* @param {Refs~callback} [callback]
* @return {*} [data]
*/
exports.Refs = Refs;