https://github.com/ortense/mediator
A minimalistic and dependency-free event mediator with internal context for front-end.
https://github.com/ortense/mediator
dependency-free emitter events mediator observer pubsub typescript typescript-library
Last synced: 8 months ago
JSON representation
A minimalistic and dependency-free event mediator with internal context for front-end.
- Host: GitHub
- URL: https://github.com/ortense/mediator
- Owner: ortense
- License: mit
- Created: 2023-10-04T00:41:33.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-03-16T00:44:41.000Z (over 2 years ago)
- Last Synced: 2025-03-01T02:34:41.811Z (over 1 year ago)
- Topics: dependency-free, emitter, events, mediator, observer, pubsub, typescript, typescript-library
- Language: TypeScript
- Homepage: https://ortense.github.io/mediator/
- Size: 1.54 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README

# @ortense/mediator
[](https://bundlephobia.com/package/@ortense/mediator) [](https://bundlephobia.com/package/@ortense/mediator) [](https://packagephobia.com/result?p=@ortense/mediator) [](https://coveralls.io/github/ortense/mediator?branch=github-actions) [](https://jsr.io/@ortense/mediator)
A minimalistic and dependency-free event mediator with internal context and middleware support for front-end.
Written typescript for a good development experience and incredibly lightweight at less than 550 bytes!
Access the complete documentation at [ortense.github.io/mediator/](https://ortense.github.io/mediator/)
## Use case
You want to simplify communication between independent components in your web app. The mediator can be used to facilitate the exchange of data and events between different parts of the application without crate a strong coupling, keeping the separation of concerns between the components of your app or external integrations like third party scripts or extensions.

## Install
Pick your favorite package manager.
```sh
npm install @ortense/mediator # npm
yarn add @ortense/mediator # yarn
pnpm add @ortense/mediator # pnpm
bun add @ortense/mediator # bun
```
## Usage
First, define an interface that extends `MediatorContext` to represent your context, this interface must be an object with properties serializable to JSON.
```typescript
export interface MyContext extends MediatorContext {
value: string
active: boolean
nested: {
items: number[]
}
}
```
Now create an object to be your initial context.
```typescript
const initialContext: MyContext = {
value: 'hello world',
active: true,
nested: {
items: [],
},
}
```
Then create the mediator object:
```typescript
export const myMediator = createMediator(initialContext)
```
The complete setup file should look like this:
```typescript
import { MediatorContext, createMediator, MediatorMiddleware } from '@ortense/mediator'
export interface MyContext extends MediatorContext {
value: string
active: boolean
nested: {
items: number[]
}
}
const initialContext: MyContext = {
value: 'hello world',
active: true,
nested: {
items: [],
},
}
// Optional: Add middleware for logging
const logger: MediatorMiddleware = (context, input, event) => {
console.log(`Event ${event} triggered with context:`, context)
}
export const myMediator = createMediator(initialContext, {
middlewares: [
{ event: '*', handler: logger }
]
})
```
### Events
The mediator use simple strings to identify events, think of it as a unique identifier to be used to send or listen to events.
Optionally, you can define a type that extends from `string` to represent the events that your mediator has.
```typescript
type MyEvents = 'loaded' | 'value:change' | 'item:added' | 'item:removed'
export const myMediator = createMediator(initialContext)
```
This is a good practice to help developers who will interact with the mediator, providing predictability of the events that can be listened or send.
### Middlewares
Middlewares provide a powerful way to intercept, transform, and control event flow in your mediator. They execute **before** event listeners and can:
- **Observe events**: Log, track, or monitor events without side effects
- **Transform data**: Modify pending changes before they're applied to the context
- **Validate changes**: Ensure data integrity and business rules
- **Cancel propagation**: Stop event processing entirely when needed
Middlewares are configured during mediator creation and run in the order they're declared.
#### Creating a Mediator with Middlewares
```typescript
import { createMediator, MediatorMiddleware } from '@ortense/mediator'
interface AppContext extends MediatorContext {
user: string
count: number
}
// Logger middleware (observes only)
const logEvents: MediatorMiddleware = (context, input, event) => {
console.log(`[${event}] Context:`, context, 'Changes:', input.pendingChanges)
// No return - passes through unchanged
}
// Validation middleware
const validateCount: MediatorMiddleware = (context, input, event) => {
if (input.pendingChanges && 'count' in input.pendingChanges && input.pendingChanges.count < 0) {
console.warn('Invalid count, cancelling event')
return { cancel: true } // Stop propagation
}
return input // Pass through
}
// Transformation middleware - adds timestamp to all changes
const addTimestamp: MediatorMiddleware = (context, input, event) => {
return {
pendingChanges: {
...(input.pendingChanges ?? {}),
timestamp: Date.now()
}
}
}
const mediator = createMediator(
{ user: 'anonymous', count: 0 },
{
middlewares: [
{ event: '*', handler: logEvents }, // Runs for all events
{ event: 'counter:decrement', handler: validateCount },
{ event: 'counter:increment', handler: addTimestamp },
]
}
)
```
#### Middleware Types
```typescript
// Input data passed to middleware functions
type MediatorMiddlewareInput = {
pendingChanges: Nullable>
}
// Cancel event propagation
type MediatorCancelEvent = {
cancel: true
}
// Middleware function signature
type MediatorMiddleware = (
context: Readonly,
input: MediatorMiddlewareInput,
event: EventName,
) => MediatorMiddlewareInput | MediatorCancelEvent | void
```
#### Middleware Return Types
```typescript
// Void middleware - observes only, passes through unchanged
const logger: MediatorMiddleware = (context, input, event) => {
console.log(`Event ${event} triggered`)
// No return - middleware passes through
}
// Transform middleware - modifies pending changes
const enrichData: MediatorMiddleware = (context, input, event) => {
return {
pendingChanges: {
...(input.pendingChanges ?? {}),
timestamp: Date.now()
}
}
}
// Cancel middleware - stops event processing
const authGuard: MediatorMiddleware = (context, input, event) => {
if (context.user === 'anonymous') {
return { cancel: true } // Stop processing
}
return input
}
```
#### Execution Flow
1. `mediator.send(event, modifier)` is called
2. A frozen snapshot of the current context is created
3. Modifier generates initial `pendingChanges` if provided
4. Middlewares execute in registration order:
- **Void middlewares** observe and pass through unchanged
- **Return middlewares** may return modified `pendingChanges`
- Any middleware can return `{ cancel: true }` to stop propagation
- **All middlewares receive the same immutable context snapshot**
5. Final context is updated with shallow merge of all `pendingChanges`
6. Event listeners run with the updated context unless propagation was cancelled
### Listening to events
To listen to events use the `.on` method
```typescript
import { myMediator, MyContext } from './my-mediator'
function myEventListener(ctx: Readonly, event: MyEvents) {
// do what you want
}
myMediator.on('loaded', myEventListener)
```
If you prefer you could use the type `MediatorEventListener`
```typescript
import { MediatorEventListener } from '@ortense/mediator'
import { myMediator, MyContext, MyEvents } from './my-mediator'
const myEventListener: MediatorEventListener = (ctx, event) => {
// do what you want
}
myMediator.on('loaded', myEventListener)
```
You also use the wildcard `*` to listen all events.
```typescript
myMediator.on('*', (ctx, event) => console.log(ctx, event))
```
Wildcard listeners could be useful for debugging, for example logging whenever an event is triggered.
```typescript
myMediator.on('*', (ctx, event) => {
console.log(`Event ${event} change the context to`, ctx)
})
```
To stop use the `.off` method
```typescript
myMediator.off('loaded', myEventListener)
```
### Send events
To send events use the `.send` method.
```typescript
import { myMediator} from './my-mediator'
myMediator.send('loaded')
```
All listener functions for the `loaded` event will be called in the order they were added to the mediator.
The `.send` method could receive a function to modifiy the context:
```typescript
import { myMediator, MyContext } from './my-mediator'
function changeValue(ctx: Readonly) {
return {
value: 'new value'
}
}
myMediator.send('value:change', changeValue)
```
If you prefer you could use the `MediatorContextModifier` type.
```typescript
import { MediatorContextModifier } from '@ortense/mediator'
import { myMediator, MyContext } from './my-mediator'
const changeValue: MediatorContextModifier = (ctx) => ({
value: 'new value'
})
myMediator.send('value:change', changeValue)
```
Or an inline declaration:
```typescript
import { myMediator } from './my-mediator'
myMediator.send('value:change', (ctx) => ({ ...ctx, active: 'new value }))
```
### Get current context
Use the method `.getContext` to get a readonly version of the current context.
```typescript
import { myMediator } from './my-mediator'
const ctx = myMediator.getContext() //? Readonly
```