diff options
author | eug-vs <eug-vs@keemail.me> | 2021-03-20 21:15:09 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2021-03-20 21:15:09 +0300 |
commit | 4940f77145a6b3bfb7c3abb14dd35d1e5e306148 (patch) | |
tree | cf059e5fa38b39bba136c5a28ccdc806d44f867e /src/services/transfers.service.ts | |
parent | 42cc6be0fc083ff5f7897a9e214918d750cb59ff (diff) | |
download | commercel-api-4940f77145a6b3bfb7c3abb14dd35d1e5e306148.tar.gz |
feat: make use of stashBefore hook
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], } }) }; |