forked from Azure/azure-sdk-for-js
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
CodeGen from PR 11935 in Azure/azure-rest-api-specs
Merge 549a175356936b49f0d310dd45259e10ac320a55 into 6000b6fde3431e4008b895f87cf39dfe598b24d1
- Loading branch information
SDKAuto
committed
Dec 3, 2020
1 parent
6c6ce54
commit d4c75f9
Showing
10 changed files
with
9,665 additions
and
619 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2020 Microsoft | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,260 +1,118 @@ | ||
# Azure Event Grid client library for JavaScript | ||
## Azure EventGridClient SDK for JavaScript | ||
|
||
[Azure Event Grid](https://azure.microsoft.com/services/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](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventgrid/eventgrid/) | | ||
[Package (NPM)](https://www.npmjs.com/package/@azure/eventgrid/v/next) | | ||
[API reference documentation](https://aka.ms/azsdk-js-eventgrid-ref-docs) | | ||
[Product documentation](https://docs.microsoft.com/azure/event-grid/) | | ||
[Samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid/samples) | ||
|
||
## Getting started | ||
This package contains an isomorphic SDK for EventGridClient. | ||
|
||
### Currently supported environments | ||
|
||
- Node.js version 8.x.x or higher | ||
- Node.js version 6.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 | ||
|
||
- An [Azure subscription][azure_sub]. | ||
- An existing [Event Grid][event_grid] Topic or Domain. If you need to create the resource, you can use the [Azure Portal][azure_portal] or [Azure CLI][azure_cli]. | ||
|
||
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 | ||
|
||
```bash | ||
az eventgrid topic create --location <location> --resource-group <your-resource-group-name> --name <your-resource-name> | ||
``` | ||
|
||
#### Create an Event Grid Domain | ||
|
||
```bash | ||
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`: | ||
### How to Install | ||
|
||
```bash | ||
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][azure_portal] or by using the [Azure CLI][azure_cli] snippet below: | ||
|
||
```bash | ||
az eventgrid topic show --name <your-resource-name> --resource-group <your-resource-group-name> --query "endpoint" | ||
``` | ||
### How to use | ||
|
||
#### Using an Access Key | ||
#### nodejs - client creation and publishEvents as an example written in TypeScript. | ||
|
||
Use the [Azure Portal][azure_portal] to browse to your Event Grid resource and retrieve an Access Key, or use the [Azure CLI][azure_cli] snippet below: | ||
##### Install @azure/ms-rest-nodeauth | ||
|
||
- Please install minimum version of `"@azure/ms-rest-nodeauth": "^3.0.0"`. | ||
```bash | ||
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: | ||
|
||
```js | ||
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid"); | ||
|
||
const client = new EventGridPublisherClient("<endpoint>", 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 `EventGridSharedAccesSignatureCredential` as follows: | ||
|
||
```js | ||
const { | ||
EventGridPublisherClient, | ||
EventGridSharedAccessSignatureCredential | ||
} = require("@azure/eventgrid"); | ||
|
||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
new EventGridSharedAccessSignatureCredential("<SAS Token>") | ||
); | ||
``` | ||
|
||
You can generate a SAS token by using the `generateSharedAccessSigniture` function. | ||
|
||
```js | ||
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](https://cloudevents.io/) is a Cloud Native Computing Foundation project which produces a specification for describing event data in a common way. Regardless of what schmea your topic or domain is configured to use, `EventGridPublisherClient` will be used to publish events to it. However, you must use the correct method for publishing: | ||
|
||
| Schema | Publishing Method | | ||
| ------------ | --------------------- | | ||
| Event Grid | `publishEvents` | | ||
| Cloud Events | `publishCloudEvents` | | ||
| Custom | `publishCustomEvents` | | ||
|
||
Using the wrong method will result in an error from the service and your events will not be published. | ||
|
||
### EventGridConsumer | ||
|
||
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 `EventGridConsumer`. | ||
|
||
Compared with using `JSON.parse` directly, `EventGridConsumer` does some additional conversions while deserializng events: | ||
|
||
1. `EventGridConsumer` validates that the required properties of an event are present and are the right types. | ||
2. `EventGridConsumer` 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. `EventGridConsumer` will decode this data back into an instance of `Uint8Array`. | ||
4. When deserilizing a _System Event_ (an event generated by another Azure service), `EventGridConsumer` 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 `EventGridConsumer` you may supply custom deserializers that are used to further convert the `data` object. | ||
|
||
## Examples | ||
|
||
### Publish a Custom Event to an Event Grid Topic | ||
|
||
```js | ||
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid"); | ||
|
||
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>")); | ||
|
||
await client.sendEvents([ | ||
{ | ||
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 | ||
|
||
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: | ||
|
||
```js | ||
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid"); | ||
|
||
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>")); | ||
|
||
await client.sendEvents([ | ||
{ | ||
topic: "my-sample-topic", | ||
eventType: "Azure.Sdk.SampleEvent", | ||
subject: "Event Subject", | ||
dataVersion: "1.0", | ||
data: { | ||
hello: "world" | ||
} | ||
} | ||
]); | ||
npm install @azure/ms-rest-nodeauth@"^3.0.0" | ||
``` | ||
|
||
### Deserializing an Event | ||
|
||
`EventGridConsumer` 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 Topic in the Cloud Events schema. Using the Service Bus SDK we can recieve these events from the Service Bus Topic and then deserialize them using `EventGridConsumer` and use `isSystemEvent` to detect what type of events they are. | ||
|
||
```js | ||
const { ServiceBusClient } = require("@azure/service-bus"); | ||
const { DefaultAzureCredential } = require("@azure/identity"); | ||
const { EventGridConsumer, isSystemEvent } = require("@azure/eventgrid"); | ||
|
||
const client = new ServiceBusClient("<service bus hostname>", new DefaultAzureCredential()); | ||
|
||
const receiver = client.createReceiver("<queue name>", "peekLock"); | ||
|
||
const consumer = new EventGridConsumer(); | ||
|
||
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.decodeCloudEvents(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 | ||
##### Sample code | ||
|
||
While the below sample uses the interactive login, other authentication options can be found in the [README.md file of @azure/ms-rest-nodeauth](https://www.npmjs.com/package/@azure/ms-rest-nodeauth) package | ||
```typescript | ||
const msRestNodeAuth = require("@azure/ms-rest-nodeauth"); | ||
const { EventGridClient } = require("@azure/eventgrid"); | ||
const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"]; | ||
|
||
msRestNodeAuth.interactiveLogin().then((creds) => { | ||
const client = new EventGridClient(creds, subscriptionId); | ||
const topicHostname = "testtopicHostname"; | ||
const events = [{ | ||
id: "testid", | ||
topic: "testtopic", | ||
subject: "testsubject", | ||
data: {}, | ||
eventType: "testeventType", | ||
eventTime: new Date().toISOString(), | ||
dataVersion: "testdataVersion" | ||
}]; | ||
client.publishEvents(topicHostname, events).then((result) => { | ||
console.log("The result is:"); | ||
console.log(result); | ||
}); | ||
}).catch((err) => { | ||
console.error(err); | ||
}); | ||
``` | ||
|
||
## Troubleshooting | ||
|
||
### Enable logs | ||
|
||
You can set the following environment variable to get the debug logging output when using this library. | ||
#### browser - Authentication, client creation and publishEvents as an example written in JavaScript. | ||
|
||
- Getting debug logs from the Azure Event Grid client library | ||
##### Install @azure/ms-rest-browserauth | ||
|
||
```bash | ||
export AZURE_LOG_LEVEL=verbose | ||
npm install @azure/ms-rest-browserauth | ||
``` | ||
|
||
For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/core/logger). | ||
|
||
## Next steps | ||
|
||
Please take a look at the | ||
[samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid/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](https://github.com/Azure/azure-sdk-for-js/blob/master/CONTRIBUTING.md) to learn more about how to build and test the code. | ||
##### Sample code | ||
|
||
See https://github.com/Azure/ms-rest-browserauth to learn how to authenticate to Azure in the browser. | ||
|
||
- index.html | ||
```html | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<title>@azure/eventgrid sample</title> | ||
<script src="node_modules/@azure/ms-rest-js/dist/msRest.browser.js"></script> | ||
<script src="node_modules/@azure/ms-rest-azure-js/dist/msRestAzure.js"></script> | ||
<script src="node_modules/@azure/ms-rest-browserauth/dist/msAuth.js"></script> | ||
<script src="node_modules/@azure/eventgrid/dist/eventgrid.js"></script> | ||
<script type="text/javascript"> | ||
const subscriptionId = "<Subscription_Id>"; | ||
const authManager = new msAuth.AuthManager({ | ||
clientId: "<client id for your Azure AD app>", | ||
tenant: "<optional tenant for your organization>" | ||
}); | ||
authManager.finalizeLogin().then((res) => { | ||
if (!res.isLoggedIn) { | ||
// may cause redirects | ||
authManager.login(); | ||
} | ||
const client = new Azure.Eventgrid.EventGridClient(res.creds, subscriptionId); | ||
const topicHostname = "testtopicHostname"; | ||
const events = [{ | ||
id: "testid", | ||
topic: "testtopic", | ||
subject: "testsubject", | ||
data: {}, | ||
eventType: "testeventType", | ||
eventTime: new Date().toISOString(), | ||
dataVersion: "testdataVersion" | ||
}]; | ||
client.publishEvents(topicHostname, events).then((result) => { | ||
console.log("The result is:"); | ||
console.log(result); | ||
}).catch((err) => { | ||
console.log("An error occurred:"); | ||
console.error(err); | ||
}); | ||
}); | ||
</script> | ||
</head> | ||
<body></body> | ||
</html> | ||
``` | ||
|
||
## Related projects | ||
|
||
- [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js) | ||
|
||
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Feventgrid%2Feventgrid%2FREADME.png) | ||
|
||
[azure_cli]: https://docs.microsoft.com/cli/azure | ||
[azure_sub]: https://azure.microsoft.com/free/ | ||
[event_grid]: https://docs.microsoft.com/azure/event-grid | ||
[azure_portal]: https://portal.azure.com | ||
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js/sdk/eventgrid/eventgrid/README.png) |
Oops, something went wrong.