CanxJS provides a unified API for sending notifications across a variety of delivery channels, including email, database, SMS, and Slack.
To create a notification, use the make:notification command:
bun run canx make:notification InvoicePaidThis class contains a via method defining the delivery channels and methods to format the message for each channel.
import { Notification, type Notifiable, type NotificationChannel } from 'canxjs';
export class InvoicePaid extends Notification {
constructor(public invoiceId: string) {
super();
}
via(notifiable: Notifiable): NotificationChannel[] {
return ['mail', 'database'];
}
toMail(notifiable: Notifiable) {
return {
subject: 'Invoice Paid',
html: `<p>Your invoice ${this.invoiceId} has been paid.</p>`
};
}
toDatabase(notifiable: Notifiable) {
return {
invoice_id: this.invoiceId,
amount: 100
};
}
}You can send notifications using the notify helper or by using the Notifiable trait on your User model.
import { notify } from 'canxjs';
import { InvoicePaid } from './notifications/InvoicePaid';
// Using the helper
await notify(user, new InvoicePaid('INV-1001'));
// Using the User model (if using Notifiable mixin)
await user.notify(new InvoicePaid('INV-1001'));The database channel stores notification information in a database table. You can access these notifications to display them in your UI.
const notifications = await Notification.where('notifiable_id', user.id).get();When using the mail channel, CanxJS attempts to send an email to the address defined in the email property of your notifiable entity.