handelse
A TypeScript library for handling events.
Installation
npm install handelse
Usage
There are two different ways to create an Event Handler. The first is to use the
createGlobal
function, which creates a global event handler. The second is to
use the createInstance
function, which creates a local event handler.
Global Event Handler
The global event handler is a singleton that can be accessed from anywhere in
your application. It is created by calling the createGlobal
function.
Since this is a singleton, it is important to use unique names for your event
handlers. If you try to create a global event handler with a name that already
exists, it will throw an error. To prevent this, we recommend using a scope
delimitted naming convention for your event handlers. Something like
my-app:testing
or my-app:testing:sub-testing
would be good examples. In the
following example, we will use my-app:testing
.
import handelse from 'handelse'
import fs from 'fs'
// anywhere in your application
handelse.createGlobal('my-app:testing', {
// options.quitEarly: Top running handlers after any returns false
// defaults to false
quitEarly: false,
// options.eventType: The type of the event to be emitted and listened to
// This helps do type checking on the emitters and listeners
// Global event handlers are not strongly typed, but this can help
eventType: 'string',
})
// anywhere later in your application
const listenerId1 = handelse.sub<string>('my-app:testing', event => {
console.log('Listening to "my-app:testing" and received event: ', event)
return true
})
// anywhere later in your application
const listenerId2 = handelse.sub<string>('my-app:testing', event => {
console.log('Also Listening to "my-app:testing" and received event: ', event)
return true
})
// anywhere later in your application
handelse.emit('my-app:testing', 'Hello World')
// anywhere later in your application to get server class only
const publisher = handelse
.get('my-app:testing', {eventType: 'string'})
.getServer()
publisher.pub('Is anyone Listening?')
publisher.pub('Hello??')
// anywhere later in your application to get a client class only
const subscriber = handelse
.get<string>('my-app:testing', {eventType: 'string'})
.getClient()
const subId = subscriber.sub(
event =>
new Promise(async res => {
console.log('Subscriber received event: ', event)
fs.appendFileSync('test.txt', `${new Date()}: ${event}\n` as string)
res(true)
}),
)
// remove the subscription after 10 seconds
setTimeout(() => subscriber.remove(subId), 10000)
// anywhere later in your application within the same scope as the listenerId1
handelse.remove('my-app:testing', listenerId1)
publisher.pub('Lorem Ipsum')
handelse.remove('my-app:testing', listenerId2)
// cleanup the global event handler
handelse.delete('my-app:testing')
Instance Event Handler
The instance event handler is a class that can be instantiated and used within a
class. It is created by calling the createInstance
function. This is useful if
you want to create a class in scope that handles events, but you don't want to
use a global event handler that is available outside of your current scope.
A use case for this would be transaction level event handling. You could create an instance event handler in a transaction scope, and then emit events within that transaction scope. The events would only be available to that single transaction.
Instance event handlers are strongly typed, so you can pass in a type for the event that is emitted and listened to. Since the handlers are passed and used directly, there is no need to name the handlers.
import {randomUUID} from 'node:crypto'
import handelse from 'handelse'
// just a simple interface to use for the example
interface User {
username: string
}
const mockStore: Record<string, User> = {}
const allPass = (res: Record<string, boolean>) =>
Object.values(res).every(v => v)
const atLeastOne = (res: Record<string, boolean>) =>
Object.values(res).length > 0
const main = async (user: User) =>
new Promise<boolean>(async res => {
const doCreate = handelse.createInstance<User>()
const preCreate = handelse.createInstance<string>()
preCreate.do(
username =>
!Boolean(Object.values(mockStore).find(u => u.username === username)),
)
doCreate.do(u => {
return preCreate
.go(u.username)
.then(allPass)
.then(checks => {
if (checks) {
const id = randomUUID()
mockStore[id] = u
return true
}
return false
})
})
return doCreate
.go(user)
.then(result => allPass(result) && atLeastOne(result))
.then(comp => res(comp))
})
const run = async () => {
await main({username: 'foo'})
await main({username: 'bar'})
await main({username: 'bar'}) // will not be added to the store (duplicate username)
}
run()
Operations
The Event System Manager exposes operations to create
(create[Global]
&
createInstance
), get
, and delete
Event Handlers, as well as operations to
directly pub
, sub
, and remove
events to global event handlers by name.
The Event Handler exposes operations to interace with events. These operations
are pub
, sub
, and remove
. These operations are aliased to make them easier
to use. The aliases are listed below.
-
pub
has the aliases:publish
,emit
,broadcast
, andsignal
-
sub
has the aliases:subscribe
,listen
, andon
-
remove
has the aliases:unsub
,unsubscribe
,off
,stop
, anddeafen
Handler Options
The Event Handler takes in an options object. The options object has the following properties.
-
quitEarly
- This option is a boolean that determines if the event handler should stop running handlers after any handler returns false.
This is useful if you want to stop running the remaining handlers after a
certain condition is met. The default value is false
. Event handlers on a
single event are NOT run in any particular order, so this option may cause
problems if you are relying on the order of the handlers on the same event.
Especially if you are rerunning the same event multiple times, different
handlers may complete while others are prevented from running due to the
quitEarly
option.
-
eventType
- (Global Event Handlers Only) This option is a string used to do simple type checking on the event listeners and emitters.
This is useful if you want to make sure that the event handlers are being used
correctly. This option is not required, but it is recommended. It is not
strongly typed, so it is not a guarantee that the event handlers are being used
correctly. For example, if you your listener expects foo|bar
ts type, but you
emit "baz"
, the simple type checker will pass, but the event handler might
still throw a type error. This is because the simple type checker is only
checking the string value, and not the type of the value like typescript does at
compile time.