Skip to content

Commit f732287

Browse files
author
SDKAuto
committed
CodeGen from PR 11695 in Azure/azure-rest-api-specs
Merge 912f3b048f9a73be0d8260a9acd6d2b85729365f into 11e915c47baf981dc5613fd782fccef4bc942a42
1 parent c4120bd commit f732287

File tree

10 files changed

+9665
-619
lines changed

10 files changed

+9665
-619
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2020 Microsoft
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

sdk/eventgrid/eventgrid/README.md

Lines changed: 88 additions & 230 deletions
Original file line numberDiff line numberDiff line change
@@ -1,260 +1,118 @@
1-
# Azure Event Grid client library for JavaScript
1+
## Azure EventGridClient SDK for JavaScript
22

3-
[Azure Event Grid](https://azure.microsoft.com/services/event-grid/) is a cloud-based service that provides reliable event delivery at massive scale.
4-
5-
Use the client library to:
6-
7-
- Send events to Event Grid using either the Event Grid, Cloud Events 1.0 schemas, or a custom schema
8-
- Decode and process events which were delivered to an Event Grid handler
9-
- Generate Shared Access Signatures for Event Grid topics
10-
11-
[Source code](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventgrid/eventgrid/) |
12-
[Package (NPM)](https://www.npmjs.com/package/@azure/eventgrid/v/next) |
13-
[API reference documentation](https://aka.ms/azsdk-js-eventgrid-ref-docs) |
14-
[Product documentation](https://docs.microsoft.com/azure/event-grid/) |
15-
[Samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid/samples)
16-
17-
## Getting started
3+
This package contains an isomorphic SDK for EventGridClient.
184

195
### Currently supported environments
206

21-
- Node.js version 8.x.x or higher
7+
- Node.js version 6.x.x or higher
228
- Browser JavaScript
23-
- Apple Safari: latest two versions
24-
- Google Chrome: latest two versions
25-
- Microsoft Edge: all supported versions
26-
- Mozilla FireFox: latest two versions
27-
28-
### Prerequisites
299

30-
- An [Azure subscription][azure_sub].
31-
- 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].
32-
33-
If you use the Azure CLI, replace `<your-resource-group-name>` and `<your-resource-name>` with your own unique names:
34-
35-
#### Create an Event Grid Topic
36-
37-
```bash
38-
az eventgrid topic create --location <location> --resource-group <your-resource-group-name> --name <your-resource-name>
39-
```
40-
41-
#### Create an Event Grid Domain
42-
43-
```bash
44-
az eventgrid domain create --location <location> --resource-group <your-resource-group-name> --name <your-resource-name>
45-
```
46-
47-
### Install the `@azure/eventgrid` package
48-
49-
Install the Azure Event Grid client library for JavaScript with `npm`:
10+
### How to Install
5011

5112
```bash
5213
npm install @azure/eventgrid
5314
```
5415

55-
### Create and authenticate a `EventGridPublisherClient`
56-
57-
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.
58-
59-
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:
60-
61-
```bash
62-
az eventgrid topic show --name <your-resource-name> --resource-group <your-resource-group-name> --query "endpoint"
63-
```
16+
### How to use
6417

65-
#### Using an Access Key
18+
#### nodejs - client creation and publishEvents as an example written in TypeScript.
6619

67-
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:
20+
##### Install @azure/ms-rest-nodeauth
6821

22+
- Please install minimum version of `"@azure/ms-rest-nodeauth": "^3.0.0"`.
6923
```bash
70-
az eventgrid topic key list --resource-group <your-resource-group-name> --name <your-event-grid-topic-name>
71-
```
72-
73-
Once you have an API key and endpoint, you can use the `AzureKeyCredential` class to authenticate the client as follows:
74-
75-
```js
76-
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");
77-
78-
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<Access Key>"));
79-
```
80-
81-
#### Using a SAS Token
82-
83-
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:
84-
85-
```js
86-
const {
87-
EventGridPublisherClient,
88-
EventGridSharedAccessSignatureCredential
89-
} = require("@azure/eventgrid");
90-
91-
const client = new EventGridPublisherClient(
92-
"<endpoint>",
93-
new EventGridSharedAccessSignatureCredential("<SAS Token>")
94-
);
95-
```
96-
97-
You can generate a SAS token by using the `generateSharedAccessSigniture` function.
98-
99-
```js
100-
const { generateSharedAccessSignature, AzureKeyCredential } = require("@azure/eventgrid");
101-
102-
// Create a SAS Token which expires on 2020-01-01 at Midnight.
103-
const token = generateSharedAccessSignature(
104-
"<endpoint>",
105-
new AzureKeyCredential("<API key>"),
106-
new Date("2020-01-01T00:00:00")
107-
);
108-
```
109-
110-
## Key concepts
111-
112-
### EventGridPublisherClient
113-
114-
`EventGridPublisherClient` is used sending events to an Event Grid Topic or an Event Grid Domain.
115-
116-
### Event Schemas
117-
118-
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:
119-
120-
| Schema | Publishing Method |
121-
| ------------ | --------------------- |
122-
| Event Grid | `publishEvents` |
123-
| Cloud Events | `publishCloudEvents` |
124-
| Custom | `publishCustomEvents` |
125-
126-
Using the wrong method will result in an error from the service and your events will not be published.
127-
128-
### EventGridConsumer
129-
130-
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`.
131-
132-
Compared with using `JSON.parse` directly, `EventGridConsumer` does some additional conversions while deserializng events:
133-
134-
1. `EventGridConsumer` validates that the required properties of an event are present and are the right types.
135-
2. `EventGridConsumer` converts the event time property into a JavaScript `Date` object.
136-
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`.
137-
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.
138-
139-
When creating an instance of `EventGridConsumer` you may supply custom deserializers that are used to further convert the `data` object.
140-
141-
## Examples
142-
143-
### Publish a Custom Event to an Event Grid Topic
144-
145-
```js
146-
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");
147-
148-
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>"));
149-
150-
await client.sendEvents([
151-
{
152-
eventType: "Azure.Sdk.SampleEvent",
153-
subject: "Event Subject",
154-
dataVersion: "1.0",
155-
data: {
156-
hello: "world"
157-
}
158-
}
159-
]);
160-
```
161-
162-
### Publish a Custom Event to a Topic in an Event Grid Domain
163-
164-
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:
165-
166-
```js
167-
const { EventGridPublisherClient, AzureKeyCredential } = require("@azure/eventgrid");
168-
169-
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>"));
170-
171-
await client.sendEvents([
172-
{
173-
topic: "my-sample-topic",
174-
eventType: "Azure.Sdk.SampleEvent",
175-
subject: "Event Subject",
176-
dataVersion: "1.0",
177-
data: {
178-
hello: "world"
179-
}
180-
}
181-
]);
24+
npm install @azure/ms-rest-nodeauth@"^3.0.0"
18225
```
18326

184-
### Deserializing an Event
185-
186-
`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.
187-
188-
```js
189-
const { ServiceBusClient } = require("@azure/service-bus");
190-
const { DefaultAzureCredential } = require("@azure/identity");
191-
const { EventGridConsumer, isSystemEvent } = require("@azure/eventgrid");
192-
193-
const client = new ServiceBusClient("<service bus hostname>", new DefaultAzureCredential());
194-
195-
const receiver = client.createReceiver("<queue name>", "peekLock");
196-
197-
const consumer = new EventGridConsumer();
198-
199-
async function processMessage(message) {
200-
// When delivering to a Service Bus Queue or Topic, EventGrid delivers a single event per message.
201-
// so we just pluck the first one.
202-
const event = (await consumer.decodeCloudEvents(message.body))[0];
203-
204-
if (isSystemEvent("Microsoft.ContainerRegistry.ImagePushed", event)) {
205-
console.log(
206-
`${event.time}: Container Registry Image Pushed event for image ${event.data.target.repository}:${event.data.target.tag}`
207-
);
208-
} else if (isSystemEvent("Microsoft.ContainerRegistry.ImageDeleted", event)) {
209-
console.log(
210-
`${event.time}: Container Registry Image Deleted event for repository ${event.data.target.repository}`
211-
);
212-
}
213-
214-
await message.complete();
215-
}
216-
217-
console.log("starting receiver");
218-
219-
receiver.subscribe({
220-
processError: async (err) => {
221-
console.error(err);
222-
},
223-
processMessage
27+
##### Sample code
28+
29+
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
30+
```typescript
31+
const msRestNodeAuth = require("@azure/ms-rest-nodeauth");
32+
const { EventGridClient } = require("@azure/eventgrid");
33+
const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"];
34+
35+
msRestNodeAuth.interactiveLogin().then((creds) => {
36+
const client = new EventGridClient(creds, subscriptionId);
37+
const topicHostname = "testtopicHostname";
38+
const events = [{
39+
id: "testid",
40+
topic: "testtopic",
41+
subject: "testsubject",
42+
data: {},
43+
eventType: "testeventType",
44+
eventTime: new Date().toISOString(),
45+
dataVersion: "testdataVersion"
46+
}];
47+
client.publishEvents(topicHostname, events).then((result) => {
48+
console.log("The result is:");
49+
console.log(result);
50+
});
51+
}).catch((err) => {
52+
console.error(err);
22453
});
22554
```
22655

227-
## Troubleshooting
228-
229-
### Enable logs
230-
231-
You can set the following environment variable to get the debug logging output when using this library.
56+
#### browser - Authentication, client creation and publishEvents as an example written in JavaScript.
23257

233-
- Getting debug logs from the Azure Event Grid client library
58+
##### Install @azure/ms-rest-browserauth
23459

23560
```bash
236-
export AZURE_LOG_LEVEL=verbose
61+
npm install @azure/ms-rest-browserauth
23762
```
23863

239-
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).
240-
241-
## Next steps
242-
243-
Please take a look at the
244-
[samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid/samples)
245-
directory for detailed examples on how to use this library.
246-
247-
## Contributing
248-
249-
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.
64+
##### Sample code
65+
66+
See https://github.com/Azure/ms-rest-browserauth to learn how to authenticate to Azure in the browser.
67+
68+
- index.html
69+
```html
70+
<!DOCTYPE html>
71+
<html lang="en">
72+
<head>
73+
<title>@azure/eventgrid sample</title>
74+
<script src="node_modules/@azure/ms-rest-js/dist/msRest.browser.js"></script>
75+
<script src="node_modules/@azure/ms-rest-azure-js/dist/msRestAzure.js"></script>
76+
<script src="node_modules/@azure/ms-rest-browserauth/dist/msAuth.js"></script>
77+
<script src="node_modules/@azure/eventgrid/dist/eventgrid.js"></script>
78+
<script type="text/javascript">
79+
const subscriptionId = "<Subscription_Id>";
80+
const authManager = new msAuth.AuthManager({
81+
clientId: "<client id for your Azure AD app>",
82+
tenant: "<optional tenant for your organization>"
83+
});
84+
authManager.finalizeLogin().then((res) => {
85+
if (!res.isLoggedIn) {
86+
// may cause redirects
87+
authManager.login();
88+
}
89+
const client = new Azure.Eventgrid.EventGridClient(res.creds, subscriptionId);
90+
const topicHostname = "testtopicHostname";
91+
const events = [{
92+
id: "testid",
93+
topic: "testtopic",
94+
subject: "testsubject",
95+
data: {},
96+
eventType: "testeventType",
97+
eventTime: new Date().toISOString(),
98+
dataVersion: "testdataVersion"
99+
}];
100+
client.publishEvents(topicHostname, events).then((result) => {
101+
console.log("The result is:");
102+
console.log(result);
103+
}).catch((err) => {
104+
console.log("An error occurred:");
105+
console.error(err);
106+
});
107+
});
108+
</script>
109+
</head>
110+
<body></body>
111+
</html>
112+
```
250113

251114
## Related projects
252115

253116
- [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js)
254117

255-
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Feventgrid%2Feventgrid%2FREADME.png)
256-
257-
[azure_cli]: https://docs.microsoft.com/cli/azure
258-
[azure_sub]: https://azure.microsoft.com/free/
259-
[event_grid]: https://docs.microsoft.com/azure/event-grid
260-
[azure_portal]: https://portal.azure.com
118+
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js/sdk/eventgrid/eventgrid/README.png)

0 commit comments

Comments
 (0)