Created
November 3, 2014 11:27
-
-
Save dwaligora/66a1bffbd0a5eb296faa to your computer and use it in GitHub Desktop.
node AR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jshint node: true*/ | |
'use strict'; | |
var _ = require('lodash'), | |
config = require('../../config.json'), | |
mysql = require('../services/mysql'); | |
/** | |
* Class responsible for handling database processing related to the brain jobs. | |
* | |
* @param {Knex} mysql knex | |
* @param {String} tableName | |
* @constructor | |
*/ | |
function JobManager(mysql, tableName) { | |
this.mysql = mysql; | |
this.dbTable = tableName; | |
} | |
/** | |
* Finds job in database according to given criteria | |
* | |
* @param {Object} where criteria object | |
* @param {Object} orderBy object literal {field: <string>, order: <string>} | |
* @param {Number} limit | |
* @param {Number} offset | |
* @returns {Promise} | |
*/ | |
JobManager.prototype.find = function(where, orderBy, limit, offset) { | |
if (!_.isPlainObject(where)) { | |
throw new Error('JobManager.find expects criteria object as a arg.'); | |
} | |
var qb = this.mysql.select('*') | |
.from(this.dbTable) | |
.where(where); | |
if (!_.isPlainObject(orderBy) && _.has('field', orderBy)) { | |
qb.orderBy(orderBy.field, orderBy.order || 'asc'); | |
} | |
if (limit) { | |
qb.limit(parseInt(limit, 10)); | |
} | |
if (offset) { | |
qb.offset(parseInt(offset, 10)); | |
} | |
return qb; | |
}; | |
/** | |
* Create new job in database | |
* | |
* @param {Object} job object | |
* @returns {Promise} | |
*/ | |
JobManager.prototype.create = function(job) { | |
if (!_.isPlainObject(job)) { | |
throw new Error('JobManager.create expects job object as a arg.'); | |
} | |
return this.mysql(this.dbTable).insert(job); | |
}; | |
/** | |
* Update the given job in database | |
* | |
* @param {Number} id | |
* @param {Object} job object | |
* @returns {Promise} | |
*/ | |
JobManager.prototype.update = function(id, job) { | |
if (!_.isPlainObject(job)) { | |
throw new Error('JobManager.update expects job object as a arg.'); | |
} | |
return this.mysql(this.dbTable) | |
.where('id', parseInt(id, 10)) | |
.update(job); | |
}; | |
module.exports = new JobManager(mysql, config.mysql.tables.jobs); | |
module.exports.Dispatcher = JobManager; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment