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

adding in ability to send in multiple args #4

Merged
merged 1 commit into from
Sep 6, 2024
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
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ export class Hookified extends Emittery {
}

// Triggers all handlers for a specific event with provided data
async hook(event: string, data: any) {
async hook(event: string, ...data: any[]) {
const eventHandlers = this._hooks.get(event);
if (eventHandlers) {
for (const handler of eventHandlers) {
try {
// eslint-disable-next-line no-await-in-loop
await handler(data);
// eslint-disable-next-line no-await-in-loop, @typescript-eslint/no-unsafe-argument
await handler(...data);
} catch (error) {
// eslint-disable-next-line no-await-in-loop
await this.emit('error', new Error(`Error in hook handler for event "${event}": ${(error as Error).message}`));
Expand Down
24 changes: 24 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,30 @@ describe('Hookified', () => {
expect(handlerData.key).toBe('modified');
});

test('execute hook and manipulate multiple data items', async () => {
const hookified = new Hookified();
const data = {key: 'value'};
const data2 = {key: 'value2'};
const data3 = {key: 'value3'};
const handlerData: Array<{key: string}> = [];

const handler = (data: {key: string}, data2: {key: string}, data3: {key: string}) => {
data.key = 'modified';
data2.key = 'foo';
data3.key = 'bar';

handlerData.push(data, data2, data3);

console.log(handlerData);
};

await hookified.onHook('event', handler);
await hookified.hook('event', data, data2, data3);
expect(handlerData[0].key).toBe('modified');
expect(handlerData[1].key).toBe('foo');
expect(handlerData[2].key).toBe('bar');
});

test('hook with error emitted', async () => {
const hookified = new Hookified();
let errorMessage;
Expand Down
Loading