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
|
var Q = require('q');
/**
* OKResource!
* TODO Would be nicer to compose this with an existing resource
* module, but haven't found a good fit. Should keep an eye on
* 'resource' by bigcompany for an update.
*/
function OKResource(options) {
if (!(this instanceof OKResource)) return new OKResource(options);
options = options || {};
if (!options.type)
throw new Error('No resource type provided to OKResource')
if (!options.schema)
throw new Error('No schema provided to OKResource');
if (!options.db)
throw new Error('No DB provided to OKResource');
var schema = options.schema;
var type = options.type;
this._db = options.db;
// Define properties which are part of the API
Object.defineProperty(this, 'schema', {
value: schema,
writable: false
});
Object.defineProperty(this, 'spec', {
value: schema.spec,
writable: false
});
Object.defineProperty(this, 'type', {
value: type,
writable: false
});
}
/**
* Throws an error if data does not conform to schema
*/
OKResource.prototype.assertValid = function(data) {
this.schema.assertValid(data);
};
OKResource.prototype.all = function() {
return this._db.getAll(this.type);
};
OKResource.prototype.create = function(data) {
return this._db.create(this.type, data);
};
OKResource.prototype.destroy = function(data) {
return this._db.remove(this.type, data.id, data);
};
OKResource.prototype.find = function(query) {
return this._db.find(this.type, query);
};
OKResource.prototype.get = function(id) {
return this._db.get(this.type, id);
};
OKResource.prototype.update = function(data) {
data = data || {};
return this._db.put(this.type, data.id, data);
};
OKResource.prototype.updateOrCreate = function(data) {
data = data || {};
var type = this.type;
var db = this._db;
return Q.promise(function(resolve, reject) {
db.get(type, data.id).then(function(cached) {
if (cached)
db.put(type, data.id, data).then(resolve, reject);
else
db.create(type, data).then(resolve, reject);
}, reject);
});
};
module.exports = OKResource;
|