/** * 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;