const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('getClientOrSupplierReference', { description: 'Returns the reference of a compensation providing a bank account', accessType: 'READ', accepts: { arg: 'bankAccount', type: 'number', required: true, description: 'The bank account of a client or a supplier' }, returns: { type: 'string', root: true }, http: { path: `/getClientOrSupplierReference`, verb: 'GET' } }); Self.getClientOrSupplierReference = async(bankAccount, options) => { const models = Self.app.models; const myOptions = {}; let reference = {}; if (typeof options == 'object') Object.assign(myOptions, options); const supplierCompensation = await models.Supplier.findOne({ where: { account: bankAccount } }, myOptions); reference.supplierId = supplierCompensation?.id; reference.supplierName = supplierCompensation?.name; let clientCompensation = {}; if (!supplierCompensation) { clientCompensation = await models.Client.findOne({ where: { accountingAccount: bankAccount } }, myOptions); reference.clientId = clientCompensation?.id; reference.clientName = clientCompensation?.name; } if (!supplierCompensation && !clientCompensation) throw new UserError('Invalid account'); return reference; }; };