var _ = require('lodash'); var path = require('path'); var lowdb = require('lowdb'); var lowdbFileAsync = require('lowdb/lib/storages/file-async'); var lowdbUnderscoreDb = require('underscore-db'); var tableName = 'customer_markups'; var Dao = function () { }; Dao.prototype.getAll = function (callback) { return db.get(tableName).value(callback); }; Dao.prototype.getById = function (id,callback) { var result = db.get(tableName).getById(id).value(); return (!result) ? callback(createError('NotFound',`ID not found: ${id}`)) : callback(null, result); }; /* should return 1..* entries for the Customer ID */ Dao.prototype.filterByAccountNumber = function(id, callback) { var results = _.filter( db.get(tableName).value(), {'organization_id': String(id)}); return (results.length === 0) ? callback(createError('NotFound',`Account number not found: ${id}`)) : callback(null, _.map(results, 'markup_info')); //note returning the markup_info object out of the db beceause // had to store it with the ID; will be different with MySql // bc we'll pass the customer Id and get the markup_info object back // from that column }; /* should return 1 entry for Customer ID, taking the first one it finds */ Dao.prototype.getByAccountNumber = function (id, callback) { var result = db.get(tableName) .find({ 'organization_id': String(id) }) .value(); return (!result) ? callback(createError('NotFound',`Account number not found: ${id}`)) : callback(null, result.markup_info); //note returning the markup_info object out of the db beceause // had to store it with the ID; will be different with MySql // bc we'll pass the customer Id and get the markup_info object back // from that column }; var createError = function(name, message){ var e = new Error(message); e.name = name; return e; }; Dao.prototype.create = function (data, callback) { return db.get(tableName) .upsert(data) .write() .then(function (value) { callback(null, value); }) .catch(function (err) { callback(err); }); }; Dao.prototype.update = function (data, callback) { return this.create(data, callback); }; Dao.prototype.deleteById = function (id, callback) { return db.get('customer_markups') .removeById(String(id)) .write() .then(function (value) { callback(null, value); }) .catch(function (err) { callback(err); }); }; module.exports = new Dao(); var dataDir = process.env.DATA_DIR || path.join(__dirname, '../../../data'); var dataPath = path.join(dataDir, tableName + '.json'); console.log('dataPath: ', dataPath); // Start lowdb database using file-async storage var db = lowdb(dataPath, { storage: lowdbFileAsync }); // needed for findById db._.mixin(lowdbUnderscoreDb);