From 1cddff7de99c6b209d35137ceb7cde3045573dc0 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Mon, 17 Aug 2020 23:40:16 +0300 Subject: feat: cleanup after poll deletion --- services/polls/polls.hooks.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'services/polls/polls.hooks.ts') diff --git a/services/polls/polls.hooks.ts b/services/polls/polls.hooks.ts index 7853c54..3bc26e8 100644 --- a/services/polls/polls.hooks.ts +++ b/services/polls/polls.hooks.ts @@ -1,5 +1,6 @@ import { HookContext } from '@feathersjs/feathers'; import { disallow } from 'feathers-hooks-common'; +import { NotAuthenticated } from '@feathersjs/errors'; import { Types } from 'mongoose'; import bluebird from 'bluebird'; import _ from 'lodash'; import { Poll } from 'which-types'; @@ -9,6 +10,7 @@ import VoteModel from '../../models/votes/vote.model'; import sortByDate from '../../hooks/sortByDate'; import signAuthority from '../../hooks/signAuthority'; import fetchImages from '../../hooks/fetchImages'; +import deleteImages from '../../hooks/deleteImages'; const convertPoll = async (context: HookContext): Promise => { @@ -44,12 +46,24 @@ const convertPoll = async (context: HookContext): Promise => { return context; }; +const onDelete = async (context: HookContext): Promise => { + const { params: { user }, service, id } = context; + if (id) { + const { author } = await service.get(id); + if (author._id.toString() !== user._id.toString()) { + throw new NotAuthenticated('You can only DELETE your own posts!'); + } + VoteModel.deleteMany({ pollId: id.toString() }); + } + return context; +}; + export default { before: { find: sortByDate, create: signAuthority, - remove: disallow('external'), + remove: [onDelete, deleteImages(['contents.left.url', 'contents.right.url'])], update: disallow('external'), patch: disallow('external') }, -- cgit v1.2.3