From 827cc9b752eecdaf63605d7dffd86f531b7e4af3 Mon Sep 17 00:00:00 2001 From: David Luecke Date: Tue, 30 Mar 2021 20:29:06 -0700 Subject: [PATCH] fix(feathers): Always enable hooks on default service methods (#2275) --- packages/feathers/src/hooks/index.ts | 4 ++-- packages/feathers/src/service.ts | 8 ++++++++ packages/feathers/test/hooks/hooks.test.ts | 11 ++++++++--- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/packages/feathers/src/hooks/index.ts b/packages/feathers/src/hooks/index.ts index b55e8db1be..d8be284c86 100644 --- a/packages/feathers/src/hooks/index.ts +++ b/packages/feathers/src/hooks/index.ts @@ -1,6 +1,6 @@ import { getManager, HookContextData, HookManager, HookMap, HOOKS, hooks, Middleware } from '@feathersjs/hooks'; import { Service, ServiceOptions, HookContext, FeathersService, Application } from '../declarations'; -import { defaultServiceArguments } from '../service'; +import { defaultServiceArguments, getHookMethods } from '../service'; import { collectLegacyHooks, enableLegacyHooks, @@ -59,7 +59,7 @@ export function hookMixin ( } const app = this; - const serviceMethodHooks = options.methods.reduce((res, method) => { + const serviceMethodHooks = getHookMethods(service, options).reduce((res, method) => { const params = (defaultServiceArguments as any)[method] || [ 'data', 'params' ]; res[method] = new FeathersHookManager(app, method) diff --git a/packages/feathers/src/service.ts b/packages/feathers/src/service.ts index d026edfcdd..f6ab028c2d 100644 --- a/packages/feathers/src/service.ts +++ b/packages/feathers/src/service.ts @@ -22,6 +22,14 @@ export const defaultEventMap = { remove: 'removed' } +export function getHookMethods (service: any, options: ServiceOptions) { + const { methods } = options; + + return defaultServiceMethods.filter(m => + typeof service[m] === 'function' && !methods.includes(m) + ).concat(methods); +} + export function getServiceOptions ( service: any, options: ServiceOptions = {} ): ServiceOptions { diff --git a/packages/feathers/test/hooks/hooks.test.ts b/packages/feathers/test/hooks/hooks.test.ts index dc57174cea..a6ecd6fb9b 100644 --- a/packages/feathers/test/hooks/hooks.test.ts +++ b/packages/feathers/test/hooks/hooks.test.ts @@ -303,12 +303,16 @@ describe('hooks basics', () => { }); }); - it('can register hooks on a custom method', async () => { + it('can register hooks on a custom method, still adds hooks to default methods', async () => { class Dummy { async get (id: Id) { return { id }; } + async create (data: any) { + return data; + } + async custom (data: any) { return data; } @@ -322,9 +326,10 @@ describe('hooks basics', () => { app.service('dummy').hooks({ custom: [async (context, next) => { - (context.data as any).fromHook = true; + context.data.fromHook = true; await next(); - }] + }], + create: [async (_context, next) => next()] }); assert.deepStrictEqual(await app.service('dummy').custom({