notifme-sdk

repository·master·Indexed 24 days ago

https://github.com/notifme/notifme-sdk

A unified notification SDK for Node.js (version 1.16.25) that simplifies sending transactional notifications across multiple channels, including Email, SMS, Push, Webpush, Slack, and Voice. It supports various provider strategies such as fallback and round-robin, and integrates with numerous third-party services like Twilio, SendGrid, and Firebase. The SDK includes a built-in logger and supports a Notification Catcher for local development testing.

Tokens
9.2K
Snippets
21
Records
59
Agent score
83%

What's inside notifme-sdk

  1. How multi-provider strategies work

    master

    A multi-provider strategy allows you to define how the SDK handles multiple providers within a single channel. You can use predefined strategies or implement a custom one.

    Predefined strategies

    Strategy nameDescription
    fallbackIf the used provider returns an error, try the next in the list.
    roundrobinUse every provider in turns. If one of them returns an error, fallback to the next.
    no-fallbackDeactivates fallback strategy.

    Custom strategies

    A custom strategy is a function that takes an array of providers and returns a Sender function: (Provider[]) => Sender.

    // Random strategy example
    const randomStrategy = (providers) => async (request) => {
      const provider = providers[Math.floor(Math.random() * providers.length)];
    
      try {
        const id = await provider.send(request)
        return {id, providerId: provider.id}
      } catch (error) {
        error.providerId = provider.id
        throw error
      }
    }
    
    new NotifmeSdk({
      channels: {
        email: {
          providers: [...],
          multiProviderStrategy: randomStrategy
        }
      }
    })
  2. Understand the `NotificationStatusType` return value

    master

    The send() method returns a Promise that resolves to a NotificationStatusType object. This object describes the outcome for each requested channel.

    type NotificationStatusType = {
      status: 'success' | 'error',
      channels?: {[channel: ChannelType]: {
        id: string,
        providerId: ?string
      }},
      errors?: {[channel: ChannelType]: Error}
    }

    Example Success Response: {status: 'success', channels: {sms: {id: 'id-116561976', providerId: 'sms-default-provider'}}}

    Example Error Response: {status: 'error', channels: {sms: {id: undefined, providerId: 'sms-notificationcatcher-provider'}}, errors: {sms: 'connect ECONNREFUSED 127.0.0.1:1025'}}

  3. Quickstart: Send a notification

    master

    To get started, import NotifmeSdk and initialize it. If you provide an empty configuration object, all providers default to console.log mode, which is useful for testing without real credentials.

    Use the .send() method and pass an object specifying the channel (e.g., sms) and its required parameters.

    import NotifmeSdk from 'notifme-sdk'
    
    const notifmeSdk = new NotifmeSdk({}) // empty config = all providers are set to console.log
    notifmeSdk
      .send({sms: {from: '+15000000000', to: '+15000000001', text: 'Hello, how are you?'}})
      .then(console.log)
  4. Setup Notification Catcher for local testing

    master

    The Notification Catcher is a web interface for viewing and testing notifications during development.

    1. Install and run the catcher as a dev dependency:
    $ yarn add --dev notification-catcher
    $ yarn run notification-catcher
    1. Enable it in your SDK configuration by setting useNotificationCatcher: true. This directs all notifications to the catcher running on port 1025.

    2. View your notifications at http://localhost:1080.

    import NotifmeSdk from 'notifme-sdk'
    
    const notifmeSdk = new NotifmeSdk({
      useNotificationCatcher: true // <= this sends all your notifications to the catcher running on port 1025
    })
    notifmeSdk
      .send({sms: {from: '+15000000000', to: '+15000000001', text: 'Hello, how are you?'}})
      .then(console.log)
  5. Configure an HTTP proxy for NotifmeSdk

    master

    To route SDK requests through an HTTP proxy, set the NOTIFME_HTTP_PROXY environment variable before running your script.

    $ NOTIFME_HTTP_PROXY=http://127.0.0.1:8580 node your-script-using-notifme.js
  6. Configure custom Notification Catcher connection settings

    master

    If your Notification Catcher is running on a custom port or domain, or requires specific connection settings, use the NOTIFME_CATCHER_OPTIONS environment variable. This variable should contain a custom connection SMTP URL (following Nodemailer SMTP URL format).

    $ # Example
    $ NOTIFME_CATCHER_OPTIONS=smtp://127.0.0.1:3025?ignoreTLS=true node your-script-using-notifme.js
  7. Initialize NotifmeSdk with general options

    master

    To use the SDK, instantiate NotifmeSdk with a configuration object. You can define notification channels and providers, or enable the useNotificationCatcher for local development.

    Important: If useNotificationCatcher is set to true, the channels configuration will be completely ignored, and all notifications will be sent to localhost:1025.

    new NotifmeSdk({
      channels: ..., // Object
      useNotificationCatcher: ... // boolean
    })
  8. Configure logging with Winston

    master

    The SDK uses winston for logging. You can configure or mute the loggers on the notifmeSdk.logger instance.

    import NotifmeSdk from 'notifme-sdk'
    import winston from 'winston'
    
    const notifmeSdk = new NotifmeSdk({})
    
    // To deactivate all loggers
    notifmeSdk.logger.mute()
    
    // Or set specific loggers
    notifmeSdk.logger.configure([
      new (winston.transports.File)({filename: 'somefile.log'})
    ])
  9. Send a notification using `notifmeSdk.send()`

    master

    Use the .send() method to dispatch notifications across one or more channels. The method accepts an object where keys are channel types (e.g., email, sms, push, webpush, slack, voice) and values are the notification payloads.

    Returns: A Promise resolving to a NotificationStatusType object indicating success or error per channel.

    // Multi-channel example
    notifmeSdk.send({
      email: {
        from: 'me@example.com',
        to: 'john@example.com',
        subject: 'Hi John',
        html: '<b>Hello John! How are you?</b>'
      },
      sms: {
        from: '+15000000000',
        to: '+15000000001',
        text: 'Hello John! How are you?'
      }
    })
  10. Configure NotifmeSdk options and channels

    master

    When initializing NotifmeSdk, you can pass a channels object to configure specific providers and strategies for each channel.

    Each channel configuration supports:

    • providers: An array of provider configurations.
    • multiProviderStrategy: Defines how to handle multiple providers (e.g., 'fallback').

    Global Options:

    • useNotificationCatcher: A boolean. If true, it overrides all channel configurations to use the notificationCatcherProvider (useful for local testing).
  11. Configure channel providers and strategies

    master

    Within the NotifmeSdk constructor, you can configure how each channel behaves using the channels option. For each channel, you can specify:

    • providers: An array of provider configurations (e.g., EmailProviderType[]).
    • multiProviderStrategy: Determines how the SDK handles multiple providers for a single channel. Available values are:
      • 'no-fallback': Does not attempt to use alternative providers if one fails.
      • 'fallback': (Default) Attempts to use the next provider in the list if the current one fails.
      • 'roundrobin': Distributes requests across providers in a rotating manner.