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
|
/**
* OKQuery!
* Takes configuration and gives you something that can run a DB query
* based on the configurations.
*/
function OKQuery(db, options) {
if (!(this instanceof OKQuery)) return new OKQuery(db, options);
options = options || {};
if (!db)
throw new Error('No DB provided to query.');
if (!options.type)
throw new Error('No resource type provided to query');
var type = options.type;
var id = options.id || '*';
Object.defineProperty(this, 'type', {
value: type,
writable: false
});
this.get = createQuery(db, type, id);
}
function createQuery(db, type, id) {
if (isDynamic(id)) {
return queryDynamic(db, type);
} else if (isSet(id)) {
return queryAll(db, type);
} else {
return querySingle(db, type, id);
}
}
function queryDynamic(db, type) {
return function(options) {
options = options || {};
return db.get(type, options.id);
}
}
function queryAll(db, type) {
return function() {
return db.getAll(type);
}
}
function querySingle(db, type, id) {
return function() {
return db.get(type, id);
}
}
function isDynamic(id) {
return id && id.charAt(0) === ':';
}
function isSet(id) {
return id && id === '*';
}
module.exports = OKQuery;
|