From f637eac6ffaa6737ea0d3f0bc64ef26267241a19 Mon Sep 17 00:00:00 2001 From: daffl Date: Fri, 10 Feb 2023 14:43:23 -0800 Subject: [PATCH] fix(hooks): Add toJSON to hook context --- main/hooks/src/base.ts | 16 ++++++++++++++++ main/hooks/test/class.test.ts | 10 ++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/main/hooks/src/base.ts b/main/hooks/src/base.ts index 41a5c6c..65af553 100644 --- a/main/hooks/src/base.ts +++ b/main/hooks/src/base.ts @@ -15,6 +15,22 @@ export class BaseHookContext { constructor(data: HookContextData = {}) { Object.assign(this, data); } + + toJSON() { + const keys = Object.keys(this); + let proto = Object.getPrototypeOf(this); + + while (proto) { + keys.push(...Object.keys(proto)); + proto = Object.getPrototypeOf(proto); + } + + return keys.reduce((result: this, key: string) => { + result[key] = this[key]; + + return result; + }, {} as this); + } } export interface HookContext extends BaseHookContext { diff --git a/main/hooks/test/class.test.ts b/main/hooks/test/class.test.ts index cdcb68a..153b663 100644 --- a/main/hooks/test/class.test.ts +++ b/main/hooks/test/class.test.ts @@ -24,10 +24,12 @@ it('hooking object on class adds to the prototype', async () => { hooks(DummyClass, { sayHi: middleware([ async (ctx: HookContext, next: NextFunction) => { - assertEquals(ctx.arguments, ['David']); - assertEquals(ctx.method, 'sayHi'); - assertEquals(ctx.name, 'David'); - assertEquals(ctx.self, instance); + assertEquals(ctx.toJSON(), { + arguments: ['David'], + method: 'sayHi', + name: 'David', + self: instance, + }); await next();