Skip to content

Commit

Permalink
adding in ability to send in multiple args
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredwray committed Sep 6, 2024
1 parent 2d795cf commit 08a98fd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
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

0 comments on commit 08a98fd

Please sign in to comment.