@benhepburn/adonis-notifications
v2.0.0
Published
A Laravel-inspired notifications provider for AdonisJS (currently only v6)
Maintainers
Readme
AdonisJS Notifications
A Laravel-inspired notifications provider for AdonisJS v6.
This package gives your application a notifications service that can dispatch a
notification through one or more configured channels. Channels are plain classes,
so you can install a community channel package or write one for your own
transport.
Requirements
- Node.js 20 or newer
- AdonisJS 6.2 or newer
Installation
Install the package with your package manager.
npm install @benhepburn/adonis-notificationspnpm add @benhepburn/adonis-notificationsyarn add @benhepburn/adonis-notificationsThen configure it inside your AdonisJS application.
node ace configure @benhepburn/adonis-notificationsThe configure command publishes config/notifications.ts and registers the
provider in adonisrc.ts.
Configuration
Register every channel your notifications may use in config/notifications.ts.
The keys in this map are the same strings returned from a notification's
via() method.
import { defineConfig } from '@benhepburn/adonis-notifications'
import { AwsSnsChannel } from '@benhepburn/adonis-notifications-aws-sns-channel'
const notificationsConfig = defineConfig({
channels: {
sms: AwsSnsChannel,
},
})
export default notificationsConfigIf a notification returns a channel key that is not configured, the service
throws ChannelNotBoundException.
Available Channels
Sending Notifications
Create a notification by extending Notification. Use via() to choose the
channels for that notification, and add channel-specific methods for the channel
classes to read.
import { Notification } from '@benhepburn/adonis-notifications'
import type { NotifiableMobile } from '@benhepburn/adonis-notifications/types'
type User = NotifiableMobile & {
name: string
}
export class WelcomeSms extends Notification<User> {
via() {
return ['sms']
}
toSms(user: User) {
return {
to: user.notificationGetMobile(),
message: `Welcome, ${user.name}`,
}
}
}Send the notification with the notifications service.
import notifications from '@benhepburn/adonis-notifications/service'
import { WelcomeSms } from '#notifications/welcome_sms'
await notifications.sendNotification(user, new WelcomeSms())You may pass a single notifiable object or an array of notifiable objects. The
notification instance receives the recipients on its notifiable property before
it is sent.
await notifications.sendNotification([userA, userB], new WelcomeSms())If any channel rejects while sending, the service throws
NotificationFailedException. The exception includes the notification instance,
the settled promise results, and a stringified version of those results.
Writing a Channel
Channels extend NotificationChannel and implement send(). Optional boot()
and shutdown() hooks are called when the handler starts and when the Adonis
provider shuts down.
import { Notification, NotificationChannel } from '@benhepburn/adonis-notifications'
type SmsNotification = Notification<any> & {
toSms(notifiable: any): {
to: string
message: string
}
}
export class SmsChannel extends NotificationChannel {
boot() {
// Initialize a client or connection here.
}
async send(notification: Notification<any>) {
const smsNotification = notification as SmsNotification
for (const notifiable of smsNotification.notifiable ?? []) {
const payload = smsNotification.toSms(notifiable)
await sendSms(payload.to, payload.message)
}
}
shutdown() {
// Close connections or flush resources here.
}
}Register the channel class in config/notifications.ts.
import { defineConfig } from '@benhepburn/adonis-notifications'
import { SmsChannel } from '#notifications/channels/sms_channel'
export default defineConfig({
channels: {
sms: SmsChannel,
},
})Testing
Use fake mode to prevent real channel classes from sending notifications. The fake handler records sent notification instances and exposes assertion helpers.
import notifications from '@benhepburn/adonis-notifications/service'
import { WelcomeSms } from '#notifications/welcome_sms'
const fake = notifications.fake()
fake.assertNotSent(WelcomeSms)
await notifications.sendNotification(user, new WelcomeSms())
fake.assertSent(WelcomeSms, 'sms')
fake.clear('sms')
fake.assertNotSent(WelcomeSms)
notifications.restore()Available fake assertions include:
assertSent(NotificationClass, via?)assertNotSent(NotificationClass, via?)clear(via?)
The via argument can be a channel key, an array of channel keys, or omitted to
target all configured channels.
Exports
The package exports:
@benhepburn/adonis-notifications:configure,defineConfig,Notification,QueuedNotification, andNotificationChannel@benhepburn/adonis-notifications/service: defaultnotificationsservice@benhepburn/adonis-notifications/types: shared TypeScript types@benhepburn/adonis-notifications/errors: package exceptions@benhepburn/adonis-notifications/notifications_provider: AdonisJS provider
Optional durable notifications
Send all notifications through sendNotification(to, notification). Classes extending
Notification send immediately; classes extending QueuedNotification are persisted
for a worker. sendNow(to, notification) explicitly bypasses queueing.
const config = defineConfig({
channels: { mail: MailChannel },
queue: {
adapter: notificationQueueAdapter,
defaults: { retry: { attempts: 5, delay: 60_000, backoff: 'exponential' } },
},
})The Adonis provider automatically discovers default-exported notification classes in
app/notifications/**/*_notification.ts (or .js in a compiled application).
There is no per-notification registration. An optional queue.directory changes the
application-relative directory. Discovery inventories paths once per process and
imports classes when sending/processing queued notifications, after application boot.
Direct users of NotificationsService must provide an absolute queue.directory.
The relative file path without its extension is the saved type, for example
wins/pending_win_review_notification. Nested paths prevent filename collisions.
Source .ts and compiled .js use the same identity; keeping both versions in the
same directory is rejected. Restart workers after adding notifications. Drain queued
jobs before renaming/moving their classes or making incompatible payload changes.
// app/notifications/review_notification.ts
export default class ReviewNotification extends QueuedNotification<NotifiableEmail> {
constructor(private winId: string) {
super()
}
toQueuePayload() {
return { winId: this.winId }
}
static fromQueuePayload(payload: NotificationPayload) {
const data = validateReviewPayload(payload)
return new ReviewNotification(data.winId)
}
queueOptions() {
return { deduplicationKey: `review:${this.winId}` }
}
async shouldSend() {
return isWinStillEligible(this.winId)
}
// Implement via() and channel methods as for any other notification.
}
await notifications.sendNotification(recipients, new ReviewNotification(winId))toQueuePayload() must return plain JSON objects, arrays, finite numbers, strings,
booleans or null. Convert dates to ISO strings, omit undefined properties, and
extract fields from models explicitly. fromQueuePayload() validates saved data
and restores dates or other values before constructing the notification. The package
snapshots the payload, recipient data and options before persistence.
Email/mobile recipients are saved as route values obtained from
notificationGetEmail() and notificationGetMobile(). Workers restore those methods;
subsequent address changes do not alter the queued snapshot. Unsupported recipients
are rejected rather than silently losing their methods.
For model lookup or other channels, supply queue.recipientCodec:
serialize(recipient) returns a JSON payload (for example a user ID), and
restore(payload) reloads the recipient in the worker. Returning undefined from
serialize falls back to the built-in routes. Lookup errors propagate for retry.
This queue envelope uses version 2 and QueuedNotificationRecord. Version 1 jobs
and the previous string-based queueNotification/factory registry API are not
supported; drain those jobs before upgrading.
Adapter and worker contract
Implement NotificationQueueAdapter.enqueue(record) (exported from /types):
- Resolve only after durable persistence. Reject enqueue failures.
- Enforce deduplication atomically on
(record.type, record.options.deduplicationKey)when supplied. Repeated submissions must not reset running or completed jobs. Document the retention window; deduplication expires when those records expire. - Honor
notBeforeand the retry policy.attemptsis the total number of tries, including the initial attempt.delayis milliseconds; exponential backoff isdelay * 2 ** (failedAttempt - 1). Defaults are merged by the service; absent retry options use the adapter's documented defaults. - Run
await notifications.deliverQueuedNotification(record)in the worker. Asentorskippedresult completes the job. Exceptions must fail the job and trigger the configured retry policy. Keep terminal failures inspectable. - Use the queue engine's normal job claiming and crash recovery. The package does not start workers, maintain locks, or implement an in-memory fallback.
Application-specific processing locks and eligibility checks belong in the
notification's shouldSend() method. Return false for stale work; throw for temporary
failures. The hook runs before any channels send, on every attempt.
Channels receive an optional second argument { queued: true } from the worker.
They must await actual delivery in that mode. Mail channel 3.0 always awaits
SMTP delivery and has no separate mail queue option. Custom channels must follow
the same contract. Multiple channels may partially succeed; retrying can resend successful
channels. SMTP and other external transports cannot guarantee exactly-once
delivery after a worker crash, even with queue deduplication.
notifications.fake() also captures durable requests without persisting them.
Use fake.assertQueued('review_notification', count) and inspect fake.queued; clear()
clears queued requests as well as sent notifications.
License
MIT
