Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(hooks): Add toJSON to hook context #108

Merged
merged 1 commit into from
Feb 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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