@grund/events

0.0.85 • Public • Published

@grund/events

This package contains two key concepts: Emitter and EventService. But before we go into these implementations, we will just define the difference between a listener and hook in grund,

  • listener
    • A listener is a subscribing function that listens to a specific event. The keyword here is that is only listens to the emitter. It should not and cannot alter the outcome of the emitted process.
  • hook
    • A hook is something that is called in a specific lifecycle process, e.g. beforeCreate and afterUpdate. This usually takes in one or several objects that is the target of the function (e.g. the object that should be created) and mutates them or returns a formatted version of the object. In other words, a hook can alter the outcome of the emitted process.

Emitter

The emitter is an object that stores events and callbacks. When creating an emitter one should pass along an EventSchema which determines what events are available.

A bit simplified, this is the interface exposed by an emitter.

interface EventSchema {
    log: (...args: any[]) => any;
}

interface Emitter<EventSchema> {
    on: <Key extends EventSchema>(key: Key, cb: EventSchema[Key]) => any
    once: <Key extends EventSchema>(key: Key, cb: EventSchema[Key]) => any

    off: <Key extends EventSchema>(key: Key, cb: EventSchema[Key]) => any
    offAll: <Key extends EventSchema>(key: Key) => any

    emit: <Key extends EventSchema> => Promise<Array<ReturnType<EventSchema[Key]>>>
}

Event service

The event service is a helper class for other services to extend. The only thing it does is to create two emitters called listeners and hooks.

So whenever another service wants to implement listeners and hooks, it just extends the EventService and can then start using the events. This is used in e.g. LoggingService and many of the auth services.

Usage

import { Event } from '@grund/events';
import { EventSchema } from './events';

class AnyService extends EventService<EventSchema> {}

const service = new AnyService();

service.listeners.on('test', () => console.log('test fired'));
service.listeners.emit('test');

Readme

Keywords

none

Package Sidebar

Install

npm i @grund/events

Weekly Downloads

1

Version

0.0.85

License

MIT

Unpacked Size

285 kB

Total Files

35

Last publish

Collaborators

  • schlagerkhan