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;