Skip to content

Commit 7901b5b

Browse files
authored
[Event Hubs] Publish samples (Azure#21811)
* [Event Hubs] Publish samples * add missing files
1 parent 427f8e6 commit 7901b5b

17 files changed

+220
-65
lines changed

sdk/eventhub/event-hubs/samples/v5/javascript/README.md

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,16 @@ urlFragment: event-hubs-javascript
1212

1313
These sample programs show how to use the JavaScript client libraries for Azure Event Hubs in some common scenarios.
1414

15-
| **File Name** | **Description** |
16-
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
17-
| [sendEvents.js][sendevents] | Demonstrates how to send events to an Event Hub. |
18-
| [receiveEvents.js][receiveevents] | Demonstrates how to use the EventHubConsumerClient to process events from all partitions of a consumer group in an Event Hub. |
19-
| [usingAadAuth.js][usingaadauth] | Demonstrates how to instantiate EventHubsClient using AAD token credentials obtained from using service principal secrets. |
20-
| [iothubConnectionString.js][iothubconnectionstring] | Demonstrates how to convert an IoT Hub connection string to an Event Hubs connection string that points to the built-in messaging endpoint. |
21-
| [iothubConnectionStringWebsockets.js][iothubconnectionstringwebsockets] | Demonstrates how to convert an IoT Hub connection string to an Event Hubs connection string that points to the built-in messaging endpoint using WebSockets. |
22-
| [useWithIotHub.js][usewithiothub] | Demonstrates how to use the EventHubConsumerClient to receive messages from an IoT Hub. |
23-
| [websockets.js][websockets] | Demonstrates how to connect to Azure Event Hubs over websockets to work over an HTTP proxy. |
15+
| **File Name** | **Description** |
16+
| ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17+
| [sendBufferedEvents.js][sendbufferedevents] | Demonstrates how to send events to an Event Hub using the `EventHubBufferedProducerClient`. This sample is different from the one in `sendEvent.ts` in that the client manages batching of events and sending after a given amount of time or after a given amount of events are in a batch instead of you managing the same explicitly. |
18+
| [sendEvents.js][sendevents] | Demonstrates how to send events to an Event Hub. |
19+
| [receiveEvents.js][receiveevents] | Demonstrates how to use the EventHubConsumerClient to process events from all partitions of a consumer group in an Event Hub. |
20+
| [usingAadAuth.js][usingaadauth] | Demonstrates how to instantiate EventHubsClient using AAD token credentials obtained from using service principal secrets. |
21+
| [iothubConnectionString.js][iothubconnectionstring] | Demonstrates how to convert an IoT Hub connection string to an Event Hubs connection string that points to the built-in messaging endpoint. |
22+
| [iothubConnectionStringWebsockets.js][iothubconnectionstringwebsockets] | Demonstrates how to convert an IoT Hub connection string to an Event Hubs connection string that points to the built-in messaging endpoint using WebSockets. |
23+
| [useWithIotHub.js][usewithiothub] | Demonstrates how to use the EventHubConsumerClient to receive messages from an IoT Hub. |
24+
| [websockets.js][websockets] | Demonstrates how to connect to Azure Event Hubs over websockets to work over an HTTP proxy. |
2425

2526
## Prerequisites
2627

@@ -49,19 +50,20 @@ npm install
4950
3. Run whichever samples you like (note that some samples may require additional setup, see the table above):
5051

5152
```bash
52-
node sendEvents.js
53+
node sendBufferedEvents.js
5354
```
5455

5556
Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform):
5657

5758
```bash
58-
npx cross-env EVENTHUB_CONNECTION_STRING="<eventhub connection string>" EVENTHUB_NAME="<eventhub name>" node sendEvents.js
59+
npx cross-env EVENTHUB_CONNECTION_STRING="<eventhub connection string>" EVENTHUB_NAME="<eventhub name>" node sendBufferedEvents.js
5960
```
6061

6162
## Next Steps
6263

6364
Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients.
6465

66+
[sendbufferedevents]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/eventhub/event-hubs/samples/v5/javascript/sendBufferedEvents.js
6567
[sendevents]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/eventhub/event-hubs/samples/v5/javascript/sendEvents.js
6668
[receiveevents]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/eventhub/event-hubs/samples/v5/javascript/receiveEvents.js
6769
[usingaadauth]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/eventhub/event-hubs/samples/v5/javascript/usingAadAuth.js

sdk/eventhub/event-hubs/samples/v5/javascript/iothubConnectionString.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ const rheaPromise = require("rhea-promise");
1919
const { EventHubConsumerClient, earliestEventPosition } = require("@azure/event-hubs");
2020

2121
// Load the .env file if it exists
22-
const dotenv = require("dotenv");
23-
dotenv.config();
22+
require("dotenv").config();
2423

2524
/**
2625
* Type guard for AmqpError.
@@ -56,9 +55,8 @@ function generateSasToken(resourceUri, signingKey, policyName, expiresInMins) {
5655
* `"Endpoint=sb://<hostname>;EntityPath=<your-iot-hub>;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>"`
5756
*/
5857
async function convertIotHubToEventHubsConnectionString(connectionString) {
59-
const { HostName, SharedAccessKeyName, SharedAccessKey } = parseConnectionString(
60-
connectionString
61-
);
58+
const { HostName, SharedAccessKeyName, SharedAccessKey } =
59+
parseConnectionString(connectionString);
6260

6361
// Verify that the required info is in the connection string.
6462
if (!HostName || !SharedAccessKey || !SharedAccessKeyName) {
@@ -88,13 +86,13 @@ async function convertIotHubToEventHubsConnectionString(connectionString) {
8886
username: `${SharedAccessKeyName}@sas.root.${iotHubName}`,
8987
port: 5671,
9088
reconnect: false,
91-
password: token
89+
password: token,
9290
});
9391
await connection.open();
9492

9593
// Create the receiver that will trigger a redirect error.
9694
const receiver = await connection.createReceiver({
97-
source: { address: `amqps://${HostName}/messages/events/$management` }
95+
source: { address: `amqps://${HostName}/messages/events/$management` },
9896
});
9997

10098
return new Promise((resolve, reject) => {
@@ -140,7 +138,7 @@ async function main() {
140138
},
141139
processError: async (err, context) => {
142140
console.log(`Error on partition "${context.partitionId}" : ${err}`);
143-
}
141+
},
144142
},
145143
{ startPosition: earliestEventPosition }
146144
);
@@ -156,3 +154,5 @@ async function main() {
156154
main().catch((error) => {
157155
console.error("Error running sample:", error);
158156
});
157+
158+
module.exports = { main };

sdk/eventhub/event-hubs/samples/v5/javascript/iothubConnectionStringWebsockets.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,12 @@
1515
const crypto = require("crypto");
1616
const { Buffer } = require("buffer");
1717
const { Connection, ReceiverEvents, parseConnectionString } = require("rhea-promise");
18-
const rheaPromise = require("rhea-promise");
18+
const rheaPromise = require("rhea-promise").default;
1919
const { EventHubConsumerClient, earliestEventPosition } = require("@azure/event-hubs");
2020
const WebSocket = require("ws");
2121

2222
// Load the .env file if it exists
23-
const dotenv = require("dotenv");
24-
dotenv.config();
23+
require("dotenv").config();
2524

2625
/**
2726
* Type guard for AmqpError.
@@ -57,9 +56,8 @@ function generateSasToken(resourceUri, signingKey, policyName, expiresInMins) {
5756
* `"Endpoint=sb://<hostname>;EntityPath=<your-iot-hub>;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>"`
5857
*/
5958
async function convertIotHubToEventHubsConnectionString(connectionString) {
60-
const { HostName, SharedAccessKeyName, SharedAccessKey } = parseConnectionString(
61-
connectionString
62-
);
59+
const { HostName, SharedAccessKeyName, SharedAccessKey } =
60+
parseConnectionString(connectionString);
6361

6462
// Verify that the required info is in the connection string.
6563
if (!HostName || !SharedAccessKey || !SharedAccessKeyName) {
@@ -93,14 +91,14 @@ async function convertIotHubToEventHubsConnectionString(connectionString) {
9391
webSocketOptions: {
9492
webSocket: WebSocket,
9593
protocol: ["AMQPWSB10"],
96-
url: `wss://${HostName}:${443}/$servicebus/websocket`
97-
}
94+
url: `wss://${HostName}:${443}/$servicebus/websocket`,
95+
},
9896
});
9997
await connection.open();
10098

10199
// Create the receiver that will trigger a redirect error.
102100
const receiver = await connection.createReceiver({
103-
source: { address: `amqps://${HostName}/messages/events/$management` }
101+
source: { address: `amqps://${HostName}/messages/events/$management` },
104102
});
105103

106104
return new Promise((resolve, reject) => {
@@ -146,7 +144,7 @@ async function main() {
146144
},
147145
processError: async (err, context) => {
148146
console.log(`Error on partition "${context.partitionId}" : ${err}`);
149-
}
147+
},
150148
},
151149
{ startPosition: earliestEventPosition }
152150
);
@@ -162,3 +160,5 @@ async function main() {
162160
main().catch((error) => {
163161
console.error("Error running sample:", error);
164162
});
163+
164+
module.exports = { main };

sdk/eventhub/event-hubs/samples/v5/javascript/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
},
2626
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/eventhub/event-hubs",
2727
"dependencies": {
28-
"@azure/event-hubs": "next",
28+
"@azure/event-hubs": "latest",
2929
"dotenv": "latest",
3030
"rhea-promise": "^2.1.0",
3131
"ws": "^8.2.0",

sdk/eventhub/event-hubs/samples/v5/javascript/receiveEvents.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
const { EventHubConsumerClient, earliestEventPosition } = require("@azure/event-hubs");
99

1010
// Load the .env file if it exists
11-
const dotenv = require("dotenv");
12-
dotenv.config();
11+
require("dotenv").config();
1312

1413
const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || "";
1514
const eventHubName = process.env["EVENTHUB_NAME"] || "";
@@ -38,7 +37,7 @@ async function main() {
3837
},
3938
processError: async (err, context) => {
4039
console.log(`Error on partition "${context.partitionId}": ${err}`);
41-
}
40+
},
4241
},
4342
{ startPosition: earliestEventPosition }
4443
);
@@ -54,3 +53,5 @@ async function main() {
5453
main().catch((error) => {
5554
console.error("Error running sample:", error);
5655
});
56+
57+
module.exports = { main };
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT Licence.
3+
4+
/**
5+
*
6+
@summary Demonstrates how to send events to an Event Hub using the `EventHubBufferedProducerClient`.
7+
* This sample is different from the one in `sendEvent.ts` in that the client manages batching of events and sending
8+
* after a given amount of time or after a given amount of events are in a batch instead of you managing the same explicitly.
9+
*/
10+
11+
const { EventHubBufferedProducerClient } = require("@azure/event-hubs");
12+
13+
// Load the .env file if it exists
14+
require("dotenv").config();
15+
16+
const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || "";
17+
const eventHubName = process.env["EVENTHUB_NAME"] || "";
18+
19+
async function handleError(ctx) {
20+
console.log(`The following error occurred:`);
21+
console.log(JSON.stringify(ctx.error, undefined, 2));
22+
console.log(
23+
`The following events were not sent as a result to the partition with ID ${ctx.partitionId}:`
24+
);
25+
for (const event of ctx.events) {
26+
console.log(JSON.stringify(event, undefined, 2));
27+
console.log("\n");
28+
}
29+
}
30+
31+
async function main() {
32+
console.log(`Running sendBufferedEvents sample`);
33+
34+
/**
35+
* Create a buffered client that batches the enqueued events and sends it either
36+
* after 750ms or after batching 1000 events, whichever occurs first.
37+
*/
38+
const client = new EventHubBufferedProducerClient(connectionString, eventHubName, {
39+
/** An error handler must be provided */
40+
onSendEventsErrorHandler: handleError,
41+
42+
/** wait for up to 750 milliseconds before sending a batch */
43+
maxWaitTimeInMs: 750,
44+
45+
/** buffer up to 1000 events per partition before sending */
46+
maxEventBufferLengthPerPartition: 1000,
47+
});
48+
49+
function createData(count) {
50+
return [...Array(count).keys()];
51+
}
52+
53+
console.log("Enqueuing events...");
54+
55+
for (const item of createData(2000)) {
56+
await client.enqueueEvent({ body: item });
57+
}
58+
59+
/**
60+
* Flushing ensures buffered events that were not sent yet will be sent before
61+
* closing the connection. Flushing can also be invoked directly using
62+
* client.flush().
63+
*/
64+
await client.close({ flush: true });
65+
console.log(`Exiting sendBufferedEvents sample`);
66+
}
67+
68+
main().catch((error) => {
69+
console.error("Error running sample:", error);
70+
process.exit(1);
71+
});
72+
73+
module.exports = { main };

sdk/eventhub/event-hubs/samples/v5/javascript/sendEvents.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
const { EventHubProducerClient } = require("@azure/event-hubs");
99

1010
// Load the .env file if it exists
11-
const dotenv = require("dotenv");
12-
dotenv.config();
11+
require("dotenv").config();
1312

1413
// Define connection string and related Event Hubs entity name here
1514
const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || "";
@@ -107,3 +106,5 @@ async function main() {
107106
main().catch((error) => {
108107
console.error("Error running sample:", error);
109108
});
109+
110+
module.exports = { main };

sdk/eventhub/event-hubs/samples/v5/javascript/useWithIotHub.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
const { EventHubConsumerClient } = require("@azure/event-hubs");
99

1010
// Load the .env file if it exists
11-
const dotenv = require("dotenv");
12-
dotenv.config();
11+
require("dotenv").config();
1312

1413
// Define IoT Hub Event Hubs-compatible connection string here.
1514
// To find the correct connection string to use, visit:
@@ -31,3 +30,5 @@ async function main() {
3130
main().catch((error) => {
3231
console.error("Error running sample:", error);
3332
});
33+
34+
module.exports = { main };

sdk/eventhub/event-hubs/samples/v5/javascript/usingAadAuth.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,7 @@ const { EventHubConsumerClient } = require("@azure/event-hubs");
2222
const { DefaultAzureCredential } = require("@azure/identity");
2323

2424
// Load the .env file if it exists
25-
const dotenv = require("dotenv");
26-
dotenv.config();
25+
require("dotenv").config();
2726

2827
// Define Event Hubs Endpoint and related entity name here here
2928
const eventHubsFullyQualifiedName = process.env["EVENTHUB_FQDN"] || ""; // <your-eventhubs-namespace>.servicebus.windows.net
@@ -54,3 +53,5 @@ async function main() {
5453
main().catch((error) => {
5554
console.error("Error running sample:", error);
5655
});
56+
57+
module.exports = { main };

sdk/eventhub/event-hubs/samples/v5/javascript/websockets.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@ const { HttpsProxyAgent } = require("https-proxy-agent");
1717
const { EventHubConsumerClient } = require("@azure/event-hubs");
1818

1919
// Load the .env file if it exists
20-
const dotenv = require("dotenv");
21-
dotenv.config();
20+
require("dotenv").config();
2221

2322
// Define connection string and related Event Hubs entity name here
2423
const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || "";
@@ -38,8 +37,8 @@ async function main() {
3837
const client = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName, {
3938
webSocketOptions: {
4039
webSocket: WebSocket,
41-
webSocketConstructorOptions: { agent: proxyAgent }
42-
}
40+
webSocketConstructorOptions: { agent: proxyAgent },
41+
},
4342
});
4443
/*
4544
Refer to other samples, and place your code here to send/receive events
@@ -52,3 +51,5 @@ async function main() {
5251
main().catch((error) => {
5352
console.error("Error running sample:", error);
5453
});
54+
55+
module.exports = { main };

0 commit comments

Comments
 (0)