blob: 6f8d7b529c9a3a49c77f93c1f9beba31761d1e14 (
plain)
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
|
/**
* OKQuery!
* Takes a query spec for a resource and maps it the proper read
* methods of that resource. This is simply to separate the notions
* of queries and resources.
*/
function OKQuery(options) {
if (!(this instanceof OKQuery)) return new OKQuery(options);
options = options || {};
if (!options.resource)
throw new Error('No resource provided to query');
var resource = options.resource;
var type = resource.type;
var query = options.query || '*';
Object.defineProperty(this, 'type', {
value: resource.type,
writable: false
});
this.get = createQuery(resource, query);
}
function createQuery(resource, query) {
if (isDynamic(query)) {
return queryDynamic(resource);
} else if (isSet(query)) {
return queryAll(resource);
} else {
return querySingle(resource, query);
}
}
function queryDynamic(resource) {
return function(id) {
return resource.get(id);
}
}
function queryAll(resource) {
return function() {
return resource.all();
}
}
function querySingle(resource, id) {
return function() {
return resource.get(id);
}
}
function isDynamic(query) {
return query && query.charAt(0) === ':';
}
function isSet(query) {
return query && query === '*';
}
module.exports = OKQuery;
|