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
|
var assign = require('object-assign');
var isobject = require('lodash.isobject');
var Q = require('q');
/**
* 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, 'resource', {
value: resource,
writable: false,
enumerable: true
});
Object.defineProperty(this, 'type', {
value: resource.type,
writable: false,
enumerable: true
});
this.get = createQuery(resource, query, {
default: options.default
});
}
function createQuery(resource, query, options) {
options = options || {};
if (resource.bound) {
query = queryBound(resource);
} else if (isobject(query)) {
query = queryComplex(resource, query)
} else if (isDynamic(query)) {
query = queryDynamic(resource);
} else if (isSet(query)) {
query = queryAll(resource);
} else {
query = querySingle(resource, query);
}
if (options.default) {
query = withDefault(query, options.default);
}
return query;
}
function queryComplex(resource, query) {
var dynamicProp;
var notDynamic = Object.keys(query).every(function(prop) {
var matcher = query[prop];
if (isDynamic(matcher)) {
dynamicProp = prop;
return false;
} else {
return true;
}
});
if (notDynamic) {
return function() {
return resource.find(query);
}
} else {
return function(id) {
var dynamicQuery = {};
dynamicQuery[dynamicProp] = id;
var query = assign({}, query, dynamicQuery);
return resource.find(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 queryBound(resource) {
return function() {
return resource.get();
};
}
function withDefault(queryFn, resultDefault) {
return function() {
return Q.Promise(function(resolve, reject) {
queryFn().then(function(data) {
data = data || resultDefault;
resolve(data);
}, reject);
});
};
}
function isDynamic(query) {
return query && query.charAt(0) === ':';
}
function isSet(query) {
return query && query === '*';
}
module.exports = OKQuery;
|