Skip to content

Commit 03e5883

Browse files
authored
fix(hooks): Add toJSON to hook context (#108)
1 parent d1ba68f commit 03e5883

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

main/hooks/src/base.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,22 @@ export class BaseHookContext<C = any> {
1515
constructor(data: HookContextData = {}) {
1616
Object.assign(this, data);
1717
}
18+
19+
toJSON() {
20+
const keys = Object.keys(this);
21+
let proto = Object.getPrototypeOf(this);
22+
23+
while (proto) {
24+
keys.push(...Object.keys(proto));
25+
proto = Object.getPrototypeOf(proto);
26+
}
27+
28+
return keys.reduce((result: this, key: string) => {
29+
result[key] = this[key];
30+
31+
return result;
32+
}, {} as this);
33+
}
1834
}
1935

2036
export interface HookContext<T = any, C = any> extends BaseHookContext<C> {

main/hooks/test/class.test.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@ it('hooking object on class adds to the prototype', async () => {
2424
hooks(DummyClass, {
2525
sayHi: middleware([
2626
async (ctx: HookContext, next: NextFunction) => {
27-
assertEquals(ctx.arguments, ['David']);
28-
assertEquals(ctx.method, 'sayHi');
29-
assertEquals(ctx.name, 'David');
30-
assertEquals(ctx.self, instance);
27+
assertEquals(ctx.toJSON(), {
28+
arguments: ['David'],
29+
method: 'sayHi',
30+
name: 'David',
31+
self: instance,
32+
});
3133

3234
await next();
3335

0 commit comments

Comments
 (0)