let loopBackContext = require('loopback-context'); let app = require('../../server/server'); module.exports = function(self) { self.setup = function() { self.super_.setup.call(this); let disableMethods = { 'create': true, 'replaceOrCreate': true, 'patchOrCreate': true, 'upsert': true, 'updateOrCreate': true, 'exists': true, 'find': true, 'findOne': true, 'findById': true, 'deleteById': true, 'replaceById': true, 'updateAttributes': false, 'createChangeStream': true, 'updateAll': true, 'upsertWithWhere': true, 'count': true }; for(let method in disableMethods) { //this.disableRemoteMethod(method, disableMethods[method]); } }; self.getUser = function() { let currentUser = loopBackContext.getCurrentContext(); let userId = currentUser.get('currentUser'); return userId; }; self.getEmployee = function() { let userId = self.getUser(); let employee = app.models.Employee; return employee.findOne({where: {userFk: userId}}); }; self.rawSql = function(query, params, cb) { this.dataSource.connector.execute(query, params, function(error, response) { cb(error, response); }); }; self.installMethod = function(methodName, filterCb) { this.remoteMethod(methodName, { description: 'List items using a filter', accessType: 'READ', accepts: [ { arg: 'filter', type: 'object', required: true, description: 'Filter defining where', http: function(ctx) { return ctx.req.query; } } ], returns: { arg: 'data', type: [this.modelName], root: true }, http: { verb: 'get', path: `/${methodName}` } }); this[methodName] = (params, cb) => { let filter = removeEmpty(filterCb(params)); var response = {} function returnValues(){ if(response.instances !== undefined && response.count !== undefined) cb(null, response); } function error(){ cb(null, response); } this.find(filter, function(err, instances) { if(!err){ response.instances = instances; returnValues(); } else{ error(); } }) this.count(filter.where, function(err, totalCount){ if(!err){ response.count = totalCount; returnValues(); } else{ error(); } }) }; }; } function removeEmpty(o) { if(Array.isArray(o)) { let array = []; for(let item of o) { let i = removeEmpty(item); if(!isEmpty(item)) array.push(item); }; if(array.length > 0) return array; } else if (typeof o === 'object') { let object = {}; for(let key in o) { let i = removeEmpty(o[key]); if(!isEmpty(i)) object[key] = i; } if(Object.keys(object).length > 0) return object; } else if (!isEmpty(o)) return o; return undefined; } function isEmpty(value) { return value === undefined || value === ""; }