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
|
var resource = require('resource');
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 type = options.type;
this._db = options.db;
this._schema = options.schema;
// this._resource = resource.define(type, {}, schema.getMschema());
// this._resource.persist(dbConfig);
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);
});
};
// /**
// * Proxy CRUD methods to underlying resource module
// * additionally wrapping them in a promise
// */
// [ 'all', 'create', 'destroy', 'find',
// 'get', 'update', 'updateOrCreate' ].forEach(function(method) {
// OKResource.prototype[method] = function() {
// var resource = this._resource;
// var args = [].slice.call(arguments);
// return Q.promise(function(resolve, reject) {
// args.push(callback);
// resource[method].apply(resource, args);
// function callback() {
// var args = [].slice.call(arguments);
// var error = args.shift();
// if (err)
// reject.call(null, err);
// else
// resolve.apply(null, args);
// }
// });
// };
// });
module.exports = OKResource;
|