diff options
Diffstat (limited to 'src/services/transfers.service.ts')
-rw-r--r-- | src/services/transfers.service.ts | 25 |
1 files changed, 9 insertions, 16 deletions
diff --git a/src/services/transfers.service.ts b/src/services/transfers.service.ts index c6fdad9..e2c70e4 100644 --- a/src/services/transfers.service.ts +++ b/src/services/transfers.service.ts @@ -1,7 +1,7 @@ import { Application } from '@feathersjs/express'; import { HookContext } from '@feathersjs/feathers'; import service from 'feathers-mongoose'; -import { populate, alterItems, getItems } from 'feathers-hooks-common'; +import { populate, alterItems, stashBefore, getItems } from 'feathers-hooks-common'; import Model from '../models/transfer/transfer.model'; import formatDate from '../hooks/formatDate'; @@ -26,26 +26,19 @@ const addFields = (item: any) => { }; const applyTransfer = async (context: HookContext): Promise<HookContext> => { - const { contractorId, amount, operation, _id } = getItems(context); + const { contractorId, amount, operation } = getItems(context); - let inc; + // If amount is not supplied, do nothing + if (!amount) return context; - // After Create / Delete - if (context.method === 'create') inc = amount; - if (context.method === 'remove') inc = -amount; - - // Before Patch / Update - else if (['patch', 'update'].includes(context.method)) { - const oldTransfer = await context.service.get(_id); - inc = amount ? (amount - oldTransfer.amount) : 0; - }; + const inc = amount - (context.params.before?.amount || 0); + const sign = (operation === 'in' ? -1 : 1) * (context.method === 'remove' ? -1 : 1); if (inc) await context.app.service('contractors').patch(contractorId, { $inc: { - debt: inc * (operation === 'in' ? -1 : 1) + debt: inc * sign } }); - return context; }; @@ -63,8 +56,8 @@ export default (app: Application): void => { remove: applyTransfer, }, before: { - patch: applyTransfer, - update: applyTransfer, + patch: [stashBefore(), applyTransfer], + update: [stashBefore(), applyTransfer], } }) }; |