Skip to content

Notifications ​

Introduction ​

A notification is a short message about something that happened (an invoice was paid, a build failed, a comment was posted) that can reach a person through more than one route: an email, a row in a database table they read in your UI, a real-time push to their browser. @plinthjs/notifications lets you describe that message once, list the channels it should use, and have a sender deliver it to each recipient.

bash
pnpm add @plinthjs/notifications

The package has no runtime dependencies. Every backend is injected: the mail transport, the database store, the broadcaster and the queue are small interfaces that you satisfy with your own code or with the other Plinth packages (Mail, Broadcasting, Queues).

Writing a notification ​

A notification extends Notification. It must implement via(), which returns the names of the channels to use for a given recipient, and it implements one payload builder per channel: toMail, toDatabase, toBroadcast, or toArray as the shared fallback.

ts
import { MailMessage, Notification, type Notifiable } from '@plinthjs/notifications'

export class InvoicePaid extends Notification {
  constructor(private readonly invoiceId: number) {
    super()
  }

  via(_notifiable: Notifiable): string[] {
    return ['mail', 'database']
  }

  toMail(_notifiable: Notifiable): MailMessage {
    return new MailMessage()
      .subject('Invoice paid')
      .greeting('Hello!')
      .line(`Invoice #${this.invoiceId} has been paid.`)
      .action('View invoice', `https://example.com/invoices/${this.invoiceId}`)
      .salutation('Regards')
      .success()
  }

  toArray(_notifiable: Notifiable): Record<string, unknown> {
    return { invoiceId: this.invoiceId }
  }
}

toDatabase and toBroadcast fall back to toArray, so one toArray is enough when both channels carry the same data. Calling a builder you did not implement throws an error naming the notification and the missing method, so a channel listed in via() without its builder fails loudly:

Notification [OnlyMail] does not implement [toArray()]. Implement it, or remove its channel from via().

Because via() receives the recipient, you can choose channels per person, for example by checking a preference:

ts
via(notifiable: Notifiable): string[] {
  return notifiable.routeNotificationFor('mail') ? ['mail', 'database'] : ['database']
}

Skipping a channel for one recipient ​

Override shouldSend(notifiable, channel) to veto a single channel for a single recipient. It runs for every channel returned by via(), and a false skips that channel only.

ts
shouldSend(notifiable: Notifiable, channel: string): boolean {
  return !(channel === 'mail' && notifiable.getKey() === 2)
}

Notifiable recipients ​

A recipient is any object that implements the Notifiable interface: getKey() returns its id, and routeNotificationFor(channel) returns where to deliver on that channel (an email address for mail, a channel name for broadcast, and so on) or undefined.

ts
import type { Notifiable } from '@plinthjs/notifications'

const user: Notifiable = {
  getKey: () => 1,
  routeNotificationFor: (channel) => (channel === 'mail' ? 'ada@example.com' : undefined),
}

A model class usually implements the two methods directly.

Notifying an address with no model ​

To notify someone who is not a stored entity, build an anonymous recipient with onDemand, or the AnonymousNotifiable class (which has a chainable route(channel, target)). Its key is always 'anonymous'.

ts
import { AnonymousNotifiable, onDemand } from '@plinthjs/notifications'

await sender.send(onDemand({ mail: 'billing@example.com' }), new InvoicePaid(44))

const guest = new AnonymousNotifiable().route('mail', 'a@example.com').route('broadcast', 'lobby')

Sending notifications ​

Create a NotificationSender with a map from channel name to channel object, then call send. The sender accepts one recipient or an array, and runs each channel returned by via() for each recipient.

ts
import {
  DatabaseChannel,
  InMemoryNotificationStore,
  MailChannel,
  NotificationSender,
} from '@plinthjs/notifications'

const store = new InMemoryNotificationStore()

const sender = new NotificationSender({
  mail: new MailChannel({
    send: async (to, message) => {
      // deliver it with your mail layer, see below
    },
  }),
  database: new DatabaseChannel(store),
})

await sender.send(user, new InvoicePaid(42)) // one recipient
await sender.send([user, otherUser], new InvoicePaid(43)) // several

If via() returns a channel that is not in the map, the sender dispatches a NotificationFailed event for it (when an events object is set) and then throws, naming the channels it does have: No notification channel registered for [slack]. Available channels: mail, database. The remaining channels are not attempted, the same as when a channel throws.

When a channel throws, the error propagates and the remaining channels and recipients are not attempted.

Channels ​

A channel implements one method, send(notifiable, notification). Three are built in, plus one for tests.

Mail ​

MailChannel renders toMail() and passes the recipient's mail route and the message to a transport you provide. The transport only needs send(to, message). A MailMessage is a small builder for the common transactional layout: subject, greeting, line (or lines), action(text, url), salutation, and a level (info by default, success() or error()) that colours the button. render() returns the fields plus ready-made text and html bodies.

ts
const rendered = new MailMessage()
  .subject('Invoice paid')
  .greeting('Hello!')
  .line('Invoice #42 has been paid.')
  .action('View invoice', 'https://example.com/invoices/42')
  .render()

rendered.text
// => 'Hello!\n\nInvoice #42 has been paid.\n\nView invoice: https://example.com/invoices/42'
rendered.level // => 'info'

All values are HTML-escaped in the html body.

To send through @plinthjs/mail, adapt the transport:

ts
import { ArrayTransport, Mailable, Mailer } from '@plinthjs/mail'

const mailer = new Mailer(new ArrayTransport())

const mailChannel = new MailChannel({
  send: async (to, message) => {
    const { subject, html, text } = message.render()
    await mailer.send(
      new Mailable()
        .to(String(to))
        .subject(subject ?? '')
        .html(html)
        .text(text),
    )
  },
})

Database ​

DatabaseChannel stores one record per notification: the recipient's key, the notification's class name as type, and the data from toDatabase(). The store only needs an insert(record) method, so you can back it with a table. InMemoryNotificationStore is a ready-made store for tests and demos.

ts
const store = new InMemoryNotificationStore()
const channel = new DatabaseChannel(store)

await new NotificationSender({ database: channel }).send(user, new InvoicePaid(42))

store.all()
// => [{ id: 'notification-1', notifiableKey: 1, type: 'InvoicePaid',
//       data: { invoiceId: 42 }, readAt: null }]

Broadcast ​

BroadcastChannel pushes toBroadcast() to a broadcaster, an object with broadcast(channels, event, payload). The event name is the notification's class name, and the payload is the broadcast data with a type field added. The target channels come from the recipient's broadcast route (a string or an array of strings), and default to notifiable.<key>, for example notifiable.1.

ts
import { BroadcastChannel, BroadcastMessage } from '@plinthjs/notifications'

class InvoicePaid extends Notification {
  // ...
  toBroadcast(): BroadcastMessage {
    return new BroadcastMessage({ invoiceId: this.invoiceId, status: 'paid' })
  }
}

const broadcast = new BroadcastChannel({
  broadcast: (channels, event, payload) => {
    // channels => ['notifiable.1'], event => 'InvoicePaid'
    // payload  => { invoiceId: 42, status: 'paid', type: 'InvoicePaid' }
  },
})

The broadcaster above takes channel names as strings. @plinthjs/broadcasting drivers take Channel objects instead; pass { channelObjects: true } and the channel hands such a driver objects with a name() (the wire name, for example private-users.3), so a driver from a BroadcastManager plugs in directly:

ts
import { BroadcastManager } from '@plinthjs/broadcasting'

const manager = new BroadcastManager({ default: 'array' })
const broadcast = new BroadcastChannel(manager.driver(), { channelObjects: true })

See Broadcasting for a broadcaster that delivers to connected clients.

Recording channel ​

ArrayChannel records every notification it receives in its sent array, with the recipient, the notification and the toArray() payload. It is useful as a stand-in channel in tests.

Database notifications ​

A stored notification can be read back and marked as read. DatabaseNotificationCollection wraps a readable store and one recipient's key. The store must also implement forNotifiable(key) and setReadAt(id, readAt), which InMemoryNotificationStore does.

ts
import { DatabaseNotificationCollection } from '@plinthjs/notifications'

const inbox = new DatabaseNotificationCollection(store, user.getKey())

const all = await inbox.all() // newest first
const unread = await inbox.unread() // rows whose readAt is null
const read = await inbox.read() // rows whose readAt is set

await inbox.markAsRead(unread[0].id) // one notification
await inbox.markAsRead() // every unread notification
await inbox.markAsUnread(unread[0].id) // back to unread
await inbox.markAsUnread() // all of them

Marking sets readAt to a timestamp in milliseconds (pass { now } to the constructor to control it). Marking an already-read notification as read leaves its original timestamp. Passing an id that does not belong to this recipient throws No database notification with id [nope] belongs to notifiable [1].

Queued notifications ​

Sending to many channels can be slow. Mark a notification as queued with queueable(notification, delaySeconds?), and give the sender a queue. For each recipient the sender then pushes a job instead of delivering immediately.

ts
import {
  queueable,
  type NotificationQueue,
  type QueuedNotificationJob,
} from '@plinthjs/notifications'

const jobs: QueuedNotificationJob[] = []
const queue: NotificationQueue = { push: (job) => void jobs.push(job) }

const sender = new NotificationSender(channels, queue)

await sender.send([user, otherUser], queueable(new InvoicePaid(5), 30))
jobs.length // => 2, one per recipient
jobs[0].delay // => 30
jobs[0].notification // => 'InvoicePaid'

await jobs[0].handle() // deliver it now

A job has notification (the class name), delay and handle(). The delay is in seconds, the same unit as later(delaySeconds, job) in the queue package, so queueable(notification, 30) means "hold for 30 seconds" and job.delay is 30. It is undefined when you passed none. Your queue decides what to do with the job, typically by wrapping it in a queue Job and calling queue.later(job.delay, ...), as below.

ts
import { ArrayQueue, Job } from '@plinthjs/queue'

const queue = new ArrayQueue()

class RunNotification extends Job {
  constructor(private readonly inner: QueuedNotificationJob) {
    super()
  }

  handle() {
    return this.inner.handle()
  }
}

sender.setQueue({
  push: async (job) => {
    if (job.delay === undefined) await queue.push(new RunNotification(job))
    else await queue.later(job.delay, new RunNotification(job))
  },
})

Without a queue argument, the sender uses runInlineQueue, which runs each job immediately, so a queued notification is still delivered. To skip the queue for one call, use sendNow.

ts
await sender.sendNow(user, queueable(new InvoicePaid(6)))

Notification events ​

Pass an events object (anything with dispatch(event)) as the third constructor argument. For every recipient and channel, the sender dispatches NotificationSending before the channel runs, then NotificationSent afterwards, or NotificationFailed (with the error) when the channel throws or is not registered, before rethrowing. Each event has notifiable, notification and channel.

ts
import { NotificationFailed, NotificationSending, NotificationSent } from '@plinthjs/notifications'

const sender = new NotificationSender(channels, undefined, {
  dispatch(event) {
    if (event instanceof NotificationSent) console.log('sent on', event.channel)
    if (event instanceof NotificationFailed) console.error(event.channel, event.error)
  },
})

Passing undefined for the queue keeps the inline default. A channel that is skipped by shouldSend produces no events.

Testing notifications ​

NotificationSender.fake() (or the exported fake()) returns a sender that records notifications without delivering them. For each recipient it records the channels via() returned after shouldSend filtering. It never calls any channel or builder, so it is safe to use in tests with no setup.

ts
import { NotificationSender } from '@plinthjs/notifications'

const sender = NotificationSender.fake()

await sender.send(user, new InvoicePaid(42))

sender
  .assertSentTo(user, InvoicePaid, (notification, channels) => channels.includes('mail'))
  .assertSentOnChannel('mail', InvoicePaid)
  .assertSentTimes(InvoicePaid, 1)
  .assertNotSentTo(otherUser, InvoicePaid)
  .assertCount(1)

sender.sent[0].channels // => ['mail', 'database']

The assertions are assertSentTo, assertNotSentTo (the class is optional), assertSentOnChannel, assertSentTimes, assertCount and assertNothingSent. They throw on failure and return the sender on success, so they chain. sentNotifications(Class, predicate?) returns the matching records.

Released under the MIT License.