Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@ibm-cloud/event-notifications-node-admin-sdk

Package Overview
Dependencies
Maintainers
19
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ibm-cloud/event-notifications-node-admin-sdk

IBM Cloud Event Notifications Admin Node.js SDK

  • 0.2.7
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2
decreased by-95.24%
Maintainers
19
Weekly downloads
 
Created
Source

IBM Cloud Event Notifications Node.js SDK

Node.js client library to interact with various Event Notifications APIs.

Table of Contents

Overview

The IBM Cloud Event Notifications Node.js SDK allows developers to programmatically interact with the Event Notifications service in IBM cloud.

Service NameImport Path
Event-Notifications@ibm-cloud/event-notifications-node-admin-sdk/event-notifications/v1

Prerequisites

  • You need an IBM Cloud account.
  • Node.js >=14: This SDK is tested with Node.js versions 14 and up. It may work on previous versions but this is not officially supported.

Installation

npm install @ibm-cloud/event-notifications-node-admin-sdk

Using the SDK

For general SDK usage information, please see this link

Initialize SDK

Initialize the sdk to connect with your Event Notifications service instance.

import { EventNotificationsV1 } from '@ibm-cloud/event-notifications-node-admin-sdk/event-notifications/v1';
import { IamAuthenticator } from '@ibm-cloud/event-notifications-node-admin-sdk/auth';

const authenticator = new IamAuthenticator({
  apikey: <apikey>,  // Event notifications service instance APIKey
});

const initParameters = {
   authenticator,
  serviceUrl: "https://" + region + ".event-notifications.cloud.ibm.com/event-notifications"
}
const eventNotificationsService = EventNotificationsV1.newInstance(initParameters);

To configure service URL for Private Endpoint

If you enabled service endpoints in your account, you can send API requests over the IBM Cloud private network. In the initialisation, the base endpoint URLs of the IAM(authenticator) & Event Notification(service) should be modified to point to private endpoints.

  1. Setting client options programmatically
const authenticator = new IamAuthenticator({
    apikey: <apikey>,  // Event notifications service instance APIKey
    url: "https://private.iam.cloud.ibm.com",
})

const initParameters = {
   authenticator,
  serviceUrl: "https://private." + region + ".event-notifications.cloud.ibm.com/event-notifications"
}
  1. Using external configuration properties
   EVENT_NOTIFICATIONS_AUTH_URL = https://private.iam.cloud.ibm.com/identity/token
  • region : Region of the Event Notifications Instance

Using the SDK

SDK Methods to consume

Source

Create Source

 const params = {
    instanceId: <instance-id>, // Event notifications service instance GUID
    name: '<source-name>',
    description: '<source-description>',
    enabled: false,
  };

  let res;
  try {
    res = await eventNotificationsService.createSources(params);
    console.log(JSON.stringify(res.result, null, 2));
    sourceId = res.result.id;
  } catch (err) {
    console.warn(err);
  }

List Sources

const params = {
  instanceId: <instance-id>, // Event notifications service instance GUID
};

eventNotificationsService
  .listSources(params)
  .then((res) => {
    console.log(JSON.stringify(res.result, null, 2));
  })
  .catch((err) => {
    console.warn(err);
  });

Get Source

const params = {
  instanceId: <instance-id>, // Event notifications service instance GUID
  id: <source-id>, // Event notifications service instance Source ID
};

eventNotificationsService
  .getSource(params)
  .then((res) => {
    console.log(JSON.stringify(res.result, null, 2));
  })
  .catch((err) => {
    console.warn(err);
  });

Update Source

const params = {
    instanceId: <instance-id>, // Event notifications service instance GUID
    id: <sourceId>,
    name: '<source-updated-name>',
    description: '<source-updated-description>',
    enabled: true,
  };

    let res;
    try {
      res = await eventNotificationsService.updateSource(params);
      console.log(JSON.stringify(res.result, null, 2));
    } catch (err) {
      console.warn(err);
    }

Delete Source

 const params = {
    instanceId: <instance-id>, // Event notifications service instance GUID
    id: <sourceId>,
  };

  try {
    await eventNotificationsService.deleteSource(params);
  } catch (err) {
    console.warn(err);
  }

Topics

Create Topic

// Rules
const rulesModel = {
  enabled: false,
  event_type_filter: "$.notification_event_info.event_type == 'cert_manager'", // Add your event type filter here.
  notification_filter: "$.notification.findings[0].severity == 'MODERATE'", // Add your notification filter here.
};

// TopicUpdateSourcesItem
const topicUpdateSourcesItemModel = {
  id: <source-id>,  // Event notifications service instance Source ID
  rules: [rulesModel],
};

const params = {
  instanceId: <instance-id>, // Event notifications service instance GUID
  name: <topic-name>,
  description: <topic-description>,
  sources: [topicUpdateSourcesItemModel],
};

eventNotificationsService
  .createTopic(params)
  .then((res) => {
    console.log(JSON.stringify(res.result, null, 2));
  })
  .catch((err) => {
    console.warn(err);
  });

List Topics

const params = {
  instanceId: <instance-id>,
};

eventNotificationsService
  .listTopics(params)
  .then((res) => {
    console.log(JSON.stringify(res.result, null, 2));
  })
  .catch((err) => {
    console.warn(err);
  });

Get Topic

const params = {
  instanceId: <instance-id>,
  id: <topic-id>,
};

eventNotificationsService
  .getTopic(params)
  .then((res) => {
    console.log(JSON.stringify(res.result, null, 2));
  })
  .catch((err) => {
    console.warn(err);
  });

Update Topic


// Rules
const rulesModel = {
  enabled: true,
  event_type_filter: "$.notification_event_info.event_type == 'cert_manager'", // Add your event type filter here.
  notification_filter: "$.notification.findings[0].severity == 'MODERATE'",  // Add your notification filter here.
};

// TopicUpdateSourcesItem
const topicUpdateSourcesItemModel = {
  id: <source-id>,
  rules: [rulesModel],
};

const params = {
  instanceId: <instance-id>,
  id: <topic-id>,
  name: <topic-update-name>,
  sources: [topicUpdateSourcesItemModel],
};

eventNotificationsService
  .replaceTopic(params)
  .then((res) => {
    console.log(JSON.stringify(res.result, null, 2));
  })
  .catch((err) => {
    console.warn(err);
  });

Delete Topic

const params = {
  instanceId : <instance-id>,
  id : <topic-id>,
}  

eventNotificationsService
.deleteTopic(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

Destinations

Create Destination

 // DestinationConfigParamsWebhookDestinationConfig
   const destinationConfigParamsModel = {
    url: <destination-config-url>,
    verb: <destination-config-verb>,
    custom_headers: {  <header-key>: <header-value> },
    sensitive_headers: [<header-key>],
  };

  // DestinationConfig
  const destinationConfigModel = {
    params: destinationConfigParamsModel,
  };

  const params = {
    instanceId: <instance-id>,
    name: <destination-name>,
    type: <destination-type>,
    description: <destination-description>,
    config: destinationConfigModel,
  };

 eventNotificationsService.createDestination(params)
 .then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

Among the supported destinations, if you need to create Push Notification destinations, you have the additional option of choosing a destination of production type or pre-production type. Set pre_prod boolean parameter to true to configure destination as pre-production destination else set the value as false. Supported destinations are Android, iOS, Chrome, Firefox and Safari.

List Destinations

const params = {
  instanceId : <instance-id>,
}

eventNotificationsService.listDestinations(params)
 .then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
.catch(err => {
    console.warn(err);
});

Get Destination

const params = {
  instanceId : <instance-id>,
  id : <destination-id>,
}

eventNotificationsService
.getDestination(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
.catch(err => {
  console.warn(err);
});

Update Destination


// DestinationConfigParamsWebhookDestinationConfig
const destinationConfigParamsModel = {
  url:  <destination-config-update-url>,
  verb: <destination-config-update-verb>,
  custom_headers: { <header-key>: <header-value> },
  sensitive_headers: [<header-key>],
};

// DestinationConfig
const destinationConfigModel = {
  params: destinationConfigParamsModel,
};
const params = {
  instanceId: <instance-id>,
  id: <destination-id>,
  name: <destination-update-name>,
  description: <destination-update-description>,
  config: destinationConfigModel,
};

eventNotificationsService.updateDestination(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

Delete Destination

const params = {
  instanceId : <instance-id>,
  id : <destination-id>,
}
eventNotificationsService
.deleteDestination(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

Custom Domain Name Verification

After creation of the custom email destination with your domain name, make sure its validated for the right ownership. This can be done with SPF and DKIM verification.

  • Sender Policy Framework (SPF), which is used to authenticate the sender of an email. SPF specifies the mail servers that are allowed to send email for your domain.
  • DomainKeys Identified Mail (DKIM), which allows an organization to take responsibility for transmitting a message by signing it. DKIM allows the receiver to check the email that claimed to have come from a specific domain, is authorized by the owner of that domain.
const updateSpfVerifyDestinationParams = {
    instanceId : <instance-id>,
    id : <destination-id>,
    type: <verification-type>,
  };

  let res;
  try {
    res = await eventNotificationsService.updateVerifyDestination(
      updateSpfVerifyDestinationParams
    );
    console.log(JSON.stringify(res.result, null, 2));
  } catch (err) {
    console.warn(err);
  }

Templates

Template is a pre-defined layout, that may include content like images, text and dynamic content based on event. Rather than creating a new content from scratch each time, you can use a template as a base and configure them in subscription. supports the following templates:

  • Custom Email notification
  • Custom Email invitation

Create Template

const templateConfigModel = {
  params: {
    body: '<!DOCTYPE html><html><head><title>IBM Event Notifications</title></head><body><p>Hello! Invitation template</p><table><tr><td>Hello invitation link:{{ ibmen_invitation }} </td></tr></table></body></html>',
    subject: 'Hi this is invitation for invitation message',
},
};
let createTemplateParams = {
  instanceId: <instance-id>,
  name: <template-name>,
  type: <template-type>,
  templateConfigModel,
  description: <template-description>,
};
let createTemplateResult;
try {
  createTemplateResult = await eventNotificationsService.createTemplate(createTemplateParams);
  console.log(JSON.stringify(createTemplateResult.result, null, 2));
} catch (err) {
  console.warn(err);
}

List Templates

const params = {
  instanceId: <instance-id>,
};

let res;
try {
  res = await eventNotificationsService.listTemplates(params);
  console.log(JSON.stringify(res.result, null, 2));
} catch (err) {
  console.warn(err);
}

Get Template

const params = {
  instanceId: <instance-id>,
  id: <template-id>,
};

let res;
try {
  res = await eventNotificationsService.getTemplate(params);
  console.log(JSON.stringify(res.result, null, 2));
} catch (err) {
  console.warn(err);
}

Update Template

const templateConfigModel = {
  params: {
    body: '<!DOCTYPE html><html><head><title>IBM Event Notifications</title></head><body><p>Hello! Invitation template</p><table><tr><td>Hello invitation link:{{ ibmen_invitation }} </td></tr></table></body></html>',
    subject: 'Hi this is invitation for invitation message',
  },
}; 
let updateTemplateParams = {
  instanceId: <instance-id>,
  name: <template-name>,
  type: <template-type>,
  templateConfigModel,
  description: <template-description>,
};
let updateTemplateResult;
try {
  updateTemplateResult = await eventNotificationsService.updateTemplate(updateTemplateParams);
} catch (err) {
  console.warn(err);
}

Delete Template

const params = {
  instanceId: <instance-id>,
  id: <template-id>,
};

try {
  await eventNotificationsService.deleteTemplate(params);
} catch (err) {
  console.warn(err);
}

Push Destination APIs

Create Destination tag subscription

const params = {
  instanceId: <instance-id>,
  id: <destination-id>,
  deviceId: <device-id>,
  tagName: <tag-name>,
};

let res;
try {
  res = await eventNotificationsService.createTagsSubscription(params);
  console.log(JSON.stringify(res.result, null, 2));
} catch (err) {
  console.warn(err);
}

List Destination tag subscription

const params = {
  instanceId: <instance-id>,
  id: <destination-id>,
};

let res;
try {
  res = await eventNotificationsService.listTagsSubscription(params);
  console.log(JSON.stringify(res.result, null, 2));
} catch (err) {
  console.warn(err);
}

Delete Destination device tag subscription

const params = {
  instanceId: <instance-id>,
  id: <destination-id>,
  deviceId: <device-id>,
  tagName: <tag-name>
};

try {
  await eventNotificationsService.deleteTagsSubscription(params);
} catch (err) {
  console.warn(err);
}

Subscriptions

Create Subscription

While Creating Subscription use any of one option from webhook or email

// SubscriptionCreateAttributesWebhookAttributes
const subscriptionCreateAttributesModel = {
  signing_enabled: false,
};

const params = {
  instanceId: <instance-id>,
  name: <subscription-name>,
  destinationId: <destination-id>,
  topicId: <topic-id>,
  attributes: subscriptionCreateAttributesModel,
  description: <subscription-description>,
};
eventNotificationsService
.createSubscription(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

List Subscriptions

const params = {
  instanceId : <instance-id>,
}
eventNotificationsService
.listSubscriptions(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

Get Subscription

const params = {
  instanceId : <instance-id>,
  id : <subscription-id>,
}
eventNotificationsService.
getSubscription(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

Update Subscription

const subscriptionUpdateAttributesModel = {
  signing_enabled: true,
};

const params = {
  instanceId: <instance-id>,
  id: <subscription-id>,
  name: <subscription-update-name>,
  description: <subscription-update-description>,
  attributes: subscriptionUpdateAttributesModel,
};
 
eventNotificationsService
.updateSubscription(params)
  .then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
.catch(err => {
  console.warn(err);
});

Delete Subscription

const params = {
  instanceId : <instance-id>,
  id : <subscription-id>,
}
eventNotificationsService
.deleteSubscription(params)
.then(res => {
  console.log(JSON.stringify(res.result, null, 2));
})
  .catch(err => {
    console.warn(err);
  });

Integration

List Integrations

const params = {
      instanceId : <instance-id>,
      offset : <offset>,
      limit : <limit>,
      search : <search>,
    };

const res = await eventNotificationsService.listIntegrations(params);

Get Integration

const params = {
  instanceId : <instance-id>,
  id: <integration-id>,
};

const res = await eventNotificationsService.getIntegration(params);

Update Integration

const metadata = {
  endpoint: <end-point>,
  crn: <crn>,
  root_key_id: <root-key-id>,
};

const params = {
  instanceId : <instance-id>,
  id: <integration-id>,
  type: <integration-type>,
  metadata,
};

const res = await eventNotificationsService.replaceIntegration(params);

Send Notifications

// NotificationFCMDevices
    const notificationDevicesModel = {
      user_ids: ['<user-ids>'],
      fcm_devices: ['<fcm-device-ids>'],
      apns_devices: ['<apns-device-ids>'],
      huawei_devices: ['<huawei-device-ids>']
      tags: ['<tag-names>'],
      platforms: ['<device-platforms>'],
    };
    
    const notificationApnsBodyModel = {
      aps: {
        alert: '<notification-message>',
        badge: 5,
      },
    };

    const notificationFcmBodyModel = {
      message: {
        'android': {
          'notification': {
              'title': '<notification-title>',
              'body': '<notification-message>'
          },
          'data': {
              'name': 'Robert',
              'description': 'notification for the Poker'
          },
        },
      }
    };

   const notificationApnsHeaders = {
     "apns-collapse-id": "<apns-apns-collapse-id-value>"
    }

   const notificationSafariBodymodel = {
      saf: {
          alert: 'Game Request',
          badge: 5,
      },
    }

    const notificationHuaweiBodymodel = {
      'android': {
          'notification': {
              'title': '<notification-title>',
              'body': '<notification-message>'
          },
          'data': {
              'name': 'Robert',
              'description': 'notification for the Poker'
          },
        },
      }

     const htmlBody =
      '"Hi  ,<br/>Certificate expiring in 90 days.<br/><br/>Please login to <a href="https: //cloud.ibm.com/security-compliance/dashboard">Security and Complaince dashboard</a> to find more information<br/>"'; 

    let notificationID = "<notification-id>"
    let notificationSubject = "<notification-subject>"
    let notificationSeverity = "<notification-severity>"
    let typeValue = "<notification-type>"
    let notificationsSouce = "<notification-source>"

const notificationCreateModel = {
      instanceId,
      ibmenseverity: notificationSeverity,
      id: notificationID,
      source: notificationsSouce,
      ibmensourceid: sourceId,
      type: typeValue,
      time: '<notification-time>',
      ibmenpushto: JSON.stringify(notificationFcmDevicesModel),
      ibmenfcmbody: JSON.stringify(notificationFcmBodyModel),
      ibmenapnsbody: JSON.stringify(notificationApnsBodyModel),
      ibmensafaribody: JSON.stringify(notificationSafariBodymodel),
      ibmenhuaweibody: JSON.stringify(notificationHuaweiBodymodel),
      ibmenmailto: JSON.stringify(['abc@ibm.com', 'def@us.ibm.com']),
      ibmensubject: 'certificate expire',
      ibmenhtmlbody: htmlBody,
      ibmendefaultshort: 'short info',
      ibmendefaultlong: 'long info',
      specversion: '1.0',
    };

    let body = notificationCreateModel;
    const sendNotificationsParams = {
      instanceId,
      body,
    };

    let res;
    try {
      res = await eventNotificationsService.sendNotifications(sendNotificationsParams);
      console.log(JSON.stringify(res.result, null, 2));
    } catch (err) {
      console.warn(err);
    }
Send Notifications Variables
  • ibmenpushto - Set up the the push notifications tragets.
    • user_ids (Array of String) - Send notification to the specified userIds.
    • fcm_devices (Array of String) - Send notification to the list of specified Android devices.
    • fcm_devices (Array of String) - Send notification to the list of specified iOS devices.
    • _devices (Array of String) - Send notification to the list of specified Chrome devices.
    • firefox_devices (Array of String) - Send notification to the list of specified Firefox devices.
    • tags (Array of String) - Send notification to the devices that have subscribed to any of these tags.
    • platforms (Array of String) - Send notification to the devices of the specified platforms.
      • Pass 'G' for google (Android) devices.
      • Pass 'A' for iOS devices.
      • Pass 'WEB_FIREFOX' for Firefox browser.
      • Pass 'WEB_CHROME' for Chrome browser.
  • Event Notifications SendNotificationsOptions - Event Notifications Send Notifications method.
    • instanceId (String) - Event Notifications instance AppGUID.
    • ibmenseverity (String) - Severity for the notifications. Some sources can have the concept of an Event severity. Hence a handy way is provided to specify a severity of the event.
    • id (String) - A unique identifier that identifies each event. source+id must be unique. The backend should be able to uniquely track this id in logs and other records. Send unique ID for each send notification. Same ID can be sent in case of failure of send notification. source+id will be logged in IBM Cloud Logging service. Using this combination we will be able to trace the event movement from one system to another and will aid in debugging and tracing.
    • source (String) - Source of the notifications. This is the identifier of the event producer. A way to uniquely identify the source of the event. For IBM Cloud services this is the crn of the service instance producing the events. For API sources this can be something the event producer backend can uniquely identify itself with.
    • ibmensourceid (String) - This is the ID of the source created in EN. This is available in the EN UI in the "Sources" section.
    • type (String) - This describes the type of event. It is of the form : This type is defined by the producer. The event type name has to be prefixed with the reverse DNS names so the event type is uniquely identified. The same event type can be produced by 2 different sources. It is highly recommended to use hyphen - as a separator instead of _.
    • time (String) - Time of the notifications. UTC time stamp when the event occurred. Must be in the RFC 3339 format.
    • ibmenpushto (string) - Targets for the FCM notifications. This contains details about the destination where you want to send push notification. This attribute is mandatory for successful delivery from an Android FCM or APNS destination
    • ibmenfcmbody (string) - Set payload string specific to Android platform [Refer this FCM official link].
    • ibmenapnsbody (string) - Set payload string specific to iOS platform [Refer this APNs official doc link].
    • ibmensafaribody (string) - Set payload string specific to safari notifications [Refer this Safari official doc link].
    • ibmenapnsheaders (string) - Set headers required for the APNs message [Refer this APNs official link(Table 1 Header fields for a POST request)]
    • ibmenchromebody (string) - Message body for the Chrome notifications. Refer this official documentation for more.
    • ibmenfirefoxbody (string) - Message body for the Firefox notifications. Refer this official documentation for more.
    • ibmenchromeheaders (string) - Headers for the Chrome notifications. Refer this official documentation for more.
    • ibmenfirefoxheaders (string) - Headers for the Firefox notifications. Refer this official documentation for more.
    • ibmendefaultshort (string) - Default short text for the message.
    • ibmendefaultlong (string) - Default long text for the message.
    • specversion (String) - Spec version of the Event Notifications. Default value is 1.0.

Set Environment

Find event_notifications_v1.env.hide in the repo and rename it to event_notifications_v1.env. After that add the values for,

  • EVENT_NOTIFICATIONS_URL - Add the Event Notifications service instance Url.
  • EVENT_NOTIFICATIONS_APIKEY - Add the Event Notifications service instance apikey.
  • EVENT_NOTIFICATIONS_GUID - Add the Event Notifications service instance GUID.

Optional

  • EVENT_NOTIFICATIONS_AUTH_URL - Add the IAM url if you are using IBM test cloud.
  • EVENT_NOTIFICATIONS_FCM_KEY - Add firebase server key for Android FCM destination.
  • EVENT_NOTIFICATIONS_FCM_ID - Add firebase sender Id for Android FCM destination.

Questions

If you are having difficulties using this SDK or have a question about the IBM Cloud services, please ask a question at Stack Overflow.

Issues

If you encounter an issue with the SDK, you are welcome to submit a bug report. Before that, please search for similar issues. It's possible someone has already encountered this issue.

Open source @ IBM

Find more open source projects on the IBM Github Page

Contributing

See CONTRIBUTING.

License

This project is released under the Apache 2.0 license. The license's full text can be found in LICENSE.

Keywords

FAQs

Package last updated on 26 Sep 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc