module.exports = Self => { Self.remoteMethod('activeDrivers', { description: 'returns actives workers 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: 'Worker', root: true }, http: { path: `/activeDrivers`, verb: 'get' } }); Self.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.firstName, em.name FROM worker em JOIN account.user ac ON em.userFk = ac.id JOIN account.role r ON r.id = ac.roleFK WHERE ac.active AND r.\`name\` = 'salesPerson' ${where} ORDER BY em.name ASC LIMIT ${limit} OFFSET ${skip}`; Self.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.firstName} ${person.name}` }); }); return results; } };