module.exports = (Vehicle) => { Vehicle.remoteMethod('activeDrivers', { description: 'returns actives employees with driver role', accessType: 'READ', accepts: [{ arg: 'filter', type: 'Object', required: false, description: 'Filter defining where and paginated data', http: {source: 'query'} }], returns: { arg: 'data', type: 'Employee', root: true }, http: { path: `/activeDrivers`, verb: 'get' } }); Vehicle.activeDrivers = (filter, callback) => { let skip = filter.skip || 0; let limit = filter.limit || 10; let where = getCondition(filter.where); // TODO: change salesPerson role to Driver role when it will be created let query = `SELECT em.id, em.name, em.surname FROM Employee em JOIN Account ac ON em.userFk = ac.id JOIN Role ON Role.id = ac.roleFK WHERE ac.active AND Role.\`name\`='salesPerson' ${where} ORDER BY em.name ASC LIMIT ${limit} OFFSET ${skip}`; Vehicle.rawSql(query, [], callback) .then(response => { callback(null, formatDriver(response)); }) .catch(reject => { callback(reject, null); }); }; function getCondition(where) { let out = []; if(typeof where === 'object') { Object.keys(where).forEach((k) => { let value = where[k]; if (typeof value === 'number') { out.push(`em.${k}=${value}`); } else if (typeof value === 'string') { out.push(`em.${k}='${value}'`); } else if (typeof value === 'boolean' || value === null) { out.push(`em.${k} IS ${String(value).toUpperCase()}`); } else if (Object.keys(value).length) { let firstProperty = Object.keys(value)[0]; out.push(`em.${k} ${firstProperty} '${value[firstProperty]}'`); } else { throw new Error ('Error: unexpected type'); } }); } return out.length ? `AND (${out.join(' AND ')})` : ''; } function formatDriver (response) { let results = []; response.forEach( person => { results.push({ id: person.id, name: `${person.name} ${person.surname}` }); }); return results; } };