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

@azure/eventgrid

Package Overview
Dependencies
Maintainers
6
Versions
327
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@azure/eventgrid

An isomorphic client library for the Azure Event Grid service.

  • 3.0.0-alpha.20210310.1
  • npm
  • Socket score

Version published
Weekly downloads
28K
increased by2.45%
Maintainers
6
Weekly downloads
 
Created
Source

Azure Event Grid client library for JavaScript

Azure Event Grid is a cloud-based service that provides reliable event delivery at massive scale.

Use the client library to:

  • Send events to Event Grid using either the Event Grid, Cloud Events 1.0 schemas, or a custom schema
  • Decode and process events which were delivered to an Event Grid handler
  • Generate Shared Access Signatures for Event Grid topics

Source code | Package (NPM) | API reference documentation | Product documentation | Samples

Getting started

Currently supported environments

  • Node.js version 8.x.x or higher
  • Browser JavaScript
    • Apple Safari: latest two versions
    • Google Chrome: latest two versions
    • Microsoft Edge: all supported versions
    • Mozilla FireFox: latest two versions

Prerequisites

If you use the Azure CLI, replace <your-resource-group-name> and <your-resource-name> with your own unique names:

Create an Event Grid Topic
az eventgrid topic create --location <location> --resource-group <your-resource-group-name> --name <your-resource-name>
Create an Event Grid Domain
az eventgrid domain create --location <location> --resource-group <your-resource-group-name> --name <your-resource-name>

Install the @azure/eventgrid package

Install the Azure Event Grid client library for JavaScript with npm:

npm install @azure/eventgrid

Create and authenticate a EventGridPublisherClient

To create a client object to access the Event Grid API, you will need the endpoint of your Event Grid topic and a credential. The Event Grid client can use either an Access Key or Shared Access Signature (SAS) created from an access key.

You can find the endpoint for your Event Grid topic either in the Azure Portal or by using the Azure CLI snippet below:

az eventgrid topic show --name <your-resource-name> --resource-group <your-resource-group-name> --query "endpoint"
Using an Access Key

Use the Azure Portal to browse to your Event Grid resource and retrieve an Access Key, or use the Azure CLI snippet below:

az eventgrid topic key list --resource-group <your-resource-group-name> --name <your-event-grid-topic-name>

Once you have an API key and endpoint, you can use the AzureKeyCredential class to authenticate the client as follows:

const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");

const client = new EventGridPublisherClient(
  "<endpoint>",
  "<endpoint schema>",
  new AzureKeyCredential("<Access Key>")
);
Using a SAS Token

Like an access key, a SAS token allows access to sending events to an Event Grid topic. Unlike an access key, which can be used until it is regenerated, a SAS token has an experation time, at which point it is no longer valid. To use a SAS token for authentication, use the AzureSASCredential as follows:

const { EventGridPublisherClient, AzureSASCredential } = require("@azure/eventgrid");

const client = new EventGridPublisherClient(
  "<endpoint>",
  "<endpoint schema>",
  new AzureSASCredential("<SAS Token>")
);

You can generate a SAS token by using the generateSharedAccessSigniture function.

const { generateSharedAccessSignature, AzureKeyCredential } = require("@azure/eventgrid");

// Create a SAS Token which expires on 2020-01-01 at Midnight.
const token = generateSharedAccessSignature(
  "<endpoint>",
  new AzureKeyCredential("<API key>"),
  new Date("2020-01-01T00:00:00")
);

Key concepts

EventGridPublisherClient

EventGridPublisherClient is used sending events to an Event Grid Topic or an Event Grid Domain.

Event Schemas

Event Grid supports multiple schemas for encoding events. When a Custom Topic or Domain is created, you specify the schema that will be used when publishing events. While you may configure your topic to use a custom schema it is more common to use the already defined Event Grid schema or CloudEvents 1.0 schema. CloudEvents is a Cloud Native Computing Foundation project which produces a specification for describing event data in a common way. When you construct the EventGridPublisherClient you must specify which schema your topic is configured to use:

If your topic is configured to use the Event Grid Schema, set "EventGrid" as the schema type:

const client = new EventGridPublisherClient(
  "<endpoint>",
  "EventGrid",
  new AzureKeyCredential("<API Key>")
);

If your topic is configured to use the Cloud Event Schema, set "CloudEvent" as the schema type:

const client = new EventGridPublisherClient(
  "<endpoint>",
  "CloudEvent",
  new AzureKeyCredential("<API Key>")
);

If your topic is configured to use a Custom Event Schema, set "Custom" as the schema type:

const client = new EventGridPublisherClient(
  "<endpoint>",
  "Custom",
  new AzureKeyCredential("<API Key>")
);

Constructing the client with a different schema than what the topic is configured to expect will result in an error from the service and your events will not be published.

You can see what input schema has been configured for an Event Grid topic by using the Azure CLI snippet below:

az eventgrid topic show --name <your-resource-name> --resource-group <your-resource-group-name> --query "inputSchema"

EventGridDeserializer

Events delivered to consumers by Event Grid are delivered as JSON. Depending on the type of consumer being delivered to, the Event Grid service may deliver one or more events as part of a single payload. While these events may be deserialized using normal JavaScript methods like JSON.parse, this library offers a helper type for deserializing events, called EventGridDeserializer.

Compared with using JSON.parse directly, EventGridDeserializer does some additional conversions while deserializng events:

  1. EventGridDeserializer validates that the required properties of an event are present and are the right types.
  2. EventGridDeserializer converts the event time property into a JavaScript Date object.
  3. When using Cloud Events, binary data may be used for an event's data property (by using Uint8Array). When the event is sent through Event Grid, it is encoded in Base 64. EventGridDeserializer will decode this data back into an instance of Uint8Array.
  4. When deserilizing a System Event (an event generated by another Azure service), EventGridDeserializer will do additional conversions so that the data object matches the corresponding interface which describes its data. When using TypeScript, these interfaces ensure you have strong typing when access properties of the data object for a system event.

When creating an instance of EventGridDeserializer you may supply custom deserializers that are used to further convert the data object.

Examples

Publish a Custom Event to an Event Grid Topic using the Event Grid Schema

const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");

const client = new EventGridPublisherClient(
  "<endpoint>",
  "EventGrid",
  new AzureKeyCredential("<API key>")
);

await client.send([
  {
    eventType: "Azure.Sdk.SampleEvent",
    subject: "Event Subject",
    dataVersion: "1.0",
    data: {
      hello: "world"
    }
  }
]);

Publish a Custom Event to a Topic in an Event Grid Domain using the Event Grid Schema

Publishing events to an Event Grid Domain is similar to publish to an Event Grid Topic, except that when using the Event Grid schema for events, you must include the topic property. When publishing events in the Cloud Events 1.0 schema, the required source property is used as the name of the topic in the domain to publish to:

const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");

const client = new EventGridPublisherClient(
  "<endpoint>",
  "EventGrid",
  new AzureKeyCredential("<API key>")
);

await client.send([
  {
    topic: "my-sample-topic",
    eventType: "Azure.Sdk.SampleEvent",
    subject: "Event Subject",
    dataVersion: "1.0",
    data: {
      hello: "world"
    }
  }
]);

Deserializing an Event

EventGridDeserializer can be used to deserialize events delivered by Event Grid. When deserializing an event, you need to know the schema used to deliver the event. In this example we have events being delivered to an Azure Service Bus Queue in the Cloud Events schema. Using the Service Bus SDK we can receive these events from the Service Bus Queue and then deserialize them using EventGridDeserializer and use isSystemEvent to detect what type of events they are.

const { ServiceBusClient } = require("@azure/service-bus");
const { DefaultAzureCredential } = require("@azure/identity");
const { EventGridDeserializer, isSystemEvent } = require("@azure/eventgrid");

const client = new ServiceBusClient("<service bus hostname>", new DefaultAzureCredential());

const receiver = client.createReceiver("<queue name>", "peekLock");

const consumer = new EventGridDeserializer();

async function processMessage(message) {
  // When delivering to a Service Bus Queue or Topic, EventGrid delivers a single event per message.
  // so we just pluck the first one.
  const event = (await consumer.deserializeCloudEvents(message.body))[0];

  if (isSystemEvent("Microsoft.ContainerRegistry.ImagePushed", event)) {
    console.log(
      `${event.time}: Container Registry Image Pushed event for image ${event.data.target.repository}:${event.data.target.tag}`
    );
  } else if (isSystemEvent("Microsoft.ContainerRegistry.ImageDeleted", event)) {
    console.log(
      `${event.time}: Container Registry Image Deleted event for repository ${event.data.target.repository}`
    );
  }

  await message.complete();
}

console.log("starting receiver");

receiver.subscribe({
  processError: async (err) => {
    console.error(err);
  },
  processMessage
});

Troubleshooting

Logging

Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the AZURE_LOG_LEVEL environment variable to info. Alternatively, logging can be enabled at runtime by calling setLogLevel in the @azure/logger:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

For more detailed instructions on how to enable logs, you can look at the @azure/logger package docs.

Next steps

Please take a look at the samples directory for detailed examples on how to use this library.

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.

Impressions

Keywords

FAQs

Package last updated on 11 Mar 2021

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