hookified
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Hookified

Async Event and Middleware Hooks

tests GitHub license codecov npm npm

Features

  • Emit Events via Emittery
  • Async Middleware Hooks for Your Methods
  • ESM / CJS and Nodejs 20+
  • Maintained on a regular basis!

Special thanks to @sindresorhus for the Emittery library. 🍻

Installation

npm install hookified --save

Usage

This was built because we constantly wanted hooks and events extended on libraires we are building such as Keyv. This is a simple way to add hooks and events (via emittery) to your libraries.

import { Hookified } from 'hookified';

class MyClass extends Hookified {
  constructor() {
    super();
  }

  async myMethodEmittingEvent() {
    await this.emit('message', 'Hello World'); //using Emittery
  }

  //with hooks you can pass data in and if they are subscribed via onHook they can modify the data
  async myMethodWithHooks() Promise<any> {
    let data = { some: 'data' };
    // do something
    await this.hook('before:myMethod2', data);

    return data;
  }
}

You can even pass in multiple arguments to the hooks:

import { Hookified } from 'hookified';

class MyClass extends Hookified {
  constructor() {
    super();
  }

  async myMethodWithHooks() Promise<any> {
    let data = { some: 'data' };
    let data2 = { some: 'data2' };
    // do something
    await this.hook('before:myMethod2', data, data2);

    return data;
  }
}

API

Please see the Emittery documentation for more information on the event emitter.

.onHook(eventName, handler)

Subscribe to a hook event.

.removeHook(eventName)

Unsubscribe from a hook event.

.hook(eventName, ...args)

Run a hook event.

.hooks

Get all hooks.

.getHooks(eventName)

Get all hooks for an event.

.clearHooks(eventName)

Development and Testing

Hookified is written in TypeScript and tests are written in vitest. To run the tests, use the following command:

To setup the environment and run the tests:

npm i && npm test

To contribute follow the Contributing Guidelines and Code of Conduct.

License

MIT & © Jared Wray

Package Sidebar

Install

npm i hookified

Weekly Downloads

401

Version

1.0.0

License

MIT

Unpacked Size

11.3 kB

Total Files

7

Last publish

Collaborators

  • jaredwray