Skip to content

Commit

Permalink
fix(hooks): Add toJSON to hook context (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
daffl committed Feb 10, 2023
1 parent d1ba68f commit 03e5883
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
16 changes: 16 additions & 0 deletions main/hooks/src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ export class BaseHookContext<C = any> {
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<T = any, C = any> extends BaseHookContext<C> {
Expand Down
10 changes: 6 additions & 4 deletions main/hooks/test/class.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down

0 comments on commit 03e5883

Please sign in to comment.