From 62c25e9d41bcbc66c5205971ae3f2df1fe1394d7 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Wed, 4 Dec 2019 13:40:43 -0800 Subject: [PATCH 01/15] Updating samples folder to make it a standalone project * Makes it simpler for users to just download the entire folder, npm install and run. * Makes it more effective for us as a testing tool since we can use it to test whatever is published. --- sdk/eventhub/event-hubs/samples/README.md | 43 +++++++------------ sdk/eventhub/event-hubs/samples/package.json | 23 ++++++++++ .../event-hubs/samples/receiveEvents.ts | 21 ++++++--- .../receiveEventsUsingCheckpointStore.ts | 28 +++++++----- sdk/eventhub/event-hubs/samples/runsamples.ts | 23 ++++++++++ sdk/eventhub/event-hubs/samples/sample.env | 28 ++++++++++++ sdk/eventhub/event-hubs/samples/sendEvents.ts | 19 +++++--- .../event-hubs/samples/useWithIotHub.ts | 17 +++++--- .../event-hubs/samples/usingAadAuth.ts | 23 ++++++---- sdk/eventhub/event-hubs/samples/websockets.ts | 21 ++++++--- 10 files changed, 174 insertions(+), 72 deletions(-) create mode 100644 sdk/eventhub/event-hubs/samples/package.json create mode 100644 sdk/eventhub/event-hubs/samples/runsamples.ts create mode 100644 sdk/eventhub/event-hubs/samples/sample.env diff --git a/sdk/eventhub/event-hubs/samples/README.md b/sdk/eventhub/event-hubs/samples/README.md index 0f466d761ebe..c81a67a3e5e4 100644 --- a/sdk/eventhub/event-hubs/samples/README.md +++ b/sdk/eventhub/event-hubs/samples/README.md @@ -6,7 +6,7 @@ The samples in this folder are for version 5.0.0 and above of this library. If y Run the below in your samples folder to install the npm package for Event Hubs library. ```bash -npm install @azure/event-hubs@next +npm install ``` ## Get connection string & Event Hubs name @@ -20,35 +20,24 @@ npm install @azure/event-hubs@next Before running a sample, update it with the connection string and the Event Hub name you have noted above. -## Running a sample +## Running samples -Start by copying the sample into a npm project. -```bash -mkdir event-hubs-samples -cd event-hubs-samples -npm init -# copy sample into this directory -``` - -If you don't have Typescript installed, then use `npm` to install it first. -```bash -npm install -g typescript -``` - -Install the `@azure/event-hubs@next` package into your project, as well as any other dependencies you might need. -```bash -npm install --save @azure/event-hubs@next -``` +1. Copy this folder to your machine. +2. Install dependencies for the samples project. + + ```bash + npm install + ``` -One way to run Typescript samples is to use `ts-node`. To install `ts-node`, run the below in your sample folder -```bash -npm install ts-node -``` +3. Rename the `sample.env` file to `.env` +4. Open the `.env` file in a text editor and fill in values related to the + sample you'd like to run. +5. Run the samples using ts-node: -Use `ts-node` to run the sample copied previously. -```bash -ts-node sample.ts -``` + For example, to run the `sendEvents.ts` sample: + ```bash + npx ts-node sendEvents.ts + ``` ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Feventhub%2Fevent-hubs%2Fsamples%2FREADME.png) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json new file mode 100644 index 000000000000..8522b8c73286 --- /dev/null +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -0,0 +1,23 @@ +{ + "name": "eventhubs-samples", + "version": "1.0.0", + "description": "The samples in this folder are for version 5.0.0 and above of this library. If you are using version 2.1.0 or lower, then please use [samples for v2.1.0](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples) instead", + "main": "dist/runsamples.js", + "scripts": { + "test": "ts-node ./runsamples.ts", + "build": "tsc -p ." + }, + "keywords": [], + "author": "", + "license": "ISC", + "devDependencies": { + "ts-node": "^8.5.4", + "typescript": "^3.7.2" + }, + "dependencies": { + "@azure/core-amqp": "next", + "@azure/event-hubs": "next", + "@azure/eventhubs-checkpointstore-blob": "next", + "rhea-promise": "^1.0.0" + } +} diff --git a/sdk/eventhub/event-hubs/samples/receiveEvents.ts b/sdk/eventhub/event-hubs/samples/receiveEvents.ts index 0b66f5ab1c5c..2fd5d5088a6c 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEvents.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEvents.ts @@ -16,11 +16,13 @@ import { EventHubConsumerClient } from "@azure/event-hubs"; -const connectionString = ""; -const eventHubName = ""; -const consumerGroup = ""; +const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || ""; +const eventHubName = process.env["EVENTHUB_NAME"] || ""; +const consumerGroup = process.env["CONSUMER_GROUP_NAME"] || ""; -async function main() { +export async function main() { + console.log(`Running receiveEvents sample`); + const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName); const subscription = consumerClient.subscribe({ @@ -45,8 +47,13 @@ async function main() { resolve(); }, 30000); }); + + console.log(`Exiting receiveEvents sample`); } -main().catch((err) => { - console.log("Error occurred: ", err); -}); +if (!process.env["RUNNING_IN_TESTS"]) { + main().catch((err) => { + console.log("Error occurred: ", err); + process.exit(1); + }); +} \ No newline at end of file diff --git a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts index 22e6efe9433d..ddae3af599a4 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts @@ -23,24 +23,25 @@ import { import { ContainerClient } from "@azure/storage-blob"; import { BlobCheckpointStore } from "@azure/eventhubs-checkpointstore-blob"; -const connectionString = ""; -const eventHubName = ""; -const storageConnectionString = ""; -const containerName = ""; -const consumerGroup = ""; +const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || ""; +const eventHubName = process.env["EVENTHUB_NAME"] || ""; +const consumerGroup = process.env["CONSUMER_GROUP_NAME"] || ""; +const storageConnectionString = process.env["STORAGE_CONNECTION_STRING"] || ""; +const containerName = process.env["STORAGE_CONTAINER_NAME"] || ""; + +export async function main() { + console.log(`Running receiveEventsUsingCheckpointStore sample`); -async function main() { // this client will be used by our eventhubs-checkpointstore-blob, which // persists any checkpoints from this session in Azure Storage const containerClient = new ContainerClient(storageConnectionString, containerName); - if (!containerClient.exists()) { + if (!(await containerClient.exists())) { await containerClient.create(); } const checkpointStore : CheckpointStore = new BlobCheckpointStore(containerClient); - const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName, checkpointStore); const subscription = consumerClient.subscribe({ @@ -75,8 +76,13 @@ async function main() { resolve(); }, 30000); }); + + console.log(`Exiting receiveEventsUsingCheckpointStore sample`); } -main().catch((err) => { - console.log("Error occurred: ", err); -}); +if (!process.env["RUNNING_IN_TESTS"]) { + main().catch((err) => { + console.log("Error occurred: ", err); + process.exit(1); + }); +} diff --git a/sdk/eventhub/event-hubs/samples/runsamples.ts b/sdk/eventhub/event-hubs/samples/runsamples.ts new file mode 100644 index 000000000000..128969cdfc99 --- /dev/null +++ b/sdk/eventhub/event-hubs/samples/runsamples.ts @@ -0,0 +1,23 @@ +import * as dotenv from "dotenv"; +dotenv.config(); + +import { main as sendEventsMain } from "./sendEvents"; +import { main as receiveEventsMain } from "./receiveEvents"; +import { main as receiveEventsUsingCheckpointStoreMain } from "./receiveEventsUsingCheckpointStore"; +import { main as useWithIotHubMain } from "./useWithIotHub"; +import { main as usingAadAuthMain } from "./usingAadAuth"; +import { main as websocketsMain } from "./websockets"; + +async function main() { + await sendEventsMain(); + await receiveEventsMain(); + await receiveEventsUsingCheckpointStoreMain(); + await useWithIotHubMain(); + await usingAadAuthMain(); + await websocketsMain(); +} + +main().catch(err => { + console.log(err); + process.exit(1); +}) \ No newline at end of file diff --git a/sdk/eventhub/event-hubs/samples/sample.env b/sdk/eventhub/event-hubs/samples/sample.env new file mode 100644 index 000000000000..f63b3f16055f --- /dev/null +++ b/sdk/eventhub/event-hubs/samples/sample.env @@ -0,0 +1,28 @@ +# Used in most samples +EVENTHUB_CONNECTION_STRING= +EVENTHUB_NAME= +EVENTHUB_FQDN=.servicebus.windows.net +CONSUMER_GROUP_NAME= + +# Used in the receiveEventsUsingCheckpointStore.ts sample +STORAGE_CONTAINER_NAME= + +# Used in the useWithIotHub.ts sample +IOTHUB_CONNECTION_STRING= + +# Used in the usingAadAuth.ts sample +# Setup : +# Please ensure that your Azure Event Hubs resource is in US East, US East 2, or West Europe +# region. AAD Role Based Access Control is not supported in other regions yet. +# Register a new application in AAD and assign the "Azure Event Hubs Data Owner (Preview)" role to it +# - See https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app +# to register a new application in the Azure Active Directory. +# - Note down the CLIENT_ID and TENANT_ID from the above step. +# - In the "Certificates & Secrets" tab, create a secret and note that down. +# - In the Azure portal, go to your Even Hubs resource and click on the Access control (IAM) +# tab. Here, assign the "Azure Event Hubs Data Owner (Preview)" role to the registered application. +# - For more information on Event Hubs RBAC setup, learn more at +# https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-role-based-access-control) +AZURE_CLIENT_ID= +AZURE_TENANT_ID= +AZURE_CLIENT_SECRET= diff --git a/sdk/eventhub/event-hubs/samples/sendEvents.ts b/sdk/eventhub/event-hubs/samples/sendEvents.ts index a9ce6c98895b..60a0e17d1f9d 100644 --- a/sdk/eventhub/event-hubs/samples/sendEvents.ts +++ b/sdk/eventhub/event-hubs/samples/sendEvents.ts @@ -12,10 +12,12 @@ import { EventHubProducerClient } from "@azure/event-hubs"; // Define connection string and related Event Hubs entity name here -const connectionString = ""; -const eventHubName = ""; +const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || ""; +const eventHubName = process.env["EVENTHUB_NAME"] || ""; + +export async function main(): Promise { + console.log(`Running sendEvents sample`); -async function main(): Promise { const producer = new EventHubProducerClient(connectionString, eventHubName); console.log("Creating and sending a batch of events..."); @@ -50,8 +52,13 @@ async function main(): Promise { } await producer.close(); + console.log(`Exiting sendEvents sample`); +} + +if (!process.env["RUNNING_IN_TESTS"]) { + main().catch((err) => { + console.log("Error occurred: ", err); + process.exit(1); + }); } -main().catch((err) => { - console.log("Error occurred: ", err); -}); diff --git a/sdk/eventhub/event-hubs/samples/useWithIotHub.ts b/sdk/eventhub/event-hubs/samples/useWithIotHub.ts index 329823d59b8b..49821fbce809 100644 --- a/sdk/eventhub/event-hubs/samples/useWithIotHub.ts +++ b/sdk/eventhub/event-hubs/samples/useWithIotHub.ts @@ -9,18 +9,23 @@ import { EventHubConsumerClient } from "@azure/event-hubs"; // Define IoT Hub Event Hubs-compatible connection string here. // To find the correct connection string to use, visit: // https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-messages-read-builtin -const connectionString = ""; -const consumerGroup = ""; +const connectionString = process.env["IOTHUB_CONNECTION_STRING"] || ""; +const consumerGroup = process.env["CONSUMER_GROUP_NAME"] || ""; -async function main(): Promise { +export async function main(): Promise { + console.log(`Running useWithIotHub sample`); const client = new EventHubConsumerClient(consumerGroup, connectionString); /* Refer to other samples, and place your code here to receive events using the above client. Please note that send operations are not supported when this client is used against an IotHub instance */ await client.close(); + console.log(`Exiting useWithIotHub sample`); } -main().catch((err) => { - console.log("Error occurred: ", err); -}); +if (!process.env["RUNNING_IN_TESTS"]) { + main().catch((err) => { + console.log("Error occurred: ", err); + process.exit(1); + }); +} diff --git a/sdk/eventhub/event-hubs/samples/usingAadAuth.ts b/sdk/eventhub/event-hubs/samples/usingAadAuth.ts index a3c2b148c983..db2c83860453 100644 --- a/sdk/eventhub/event-hubs/samples/usingAadAuth.ts +++ b/sdk/eventhub/event-hubs/samples/usingAadAuth.ts @@ -26,22 +26,29 @@ import { EventHubConsumerClient } from "@azure/event-hubs"; import { DefaultAzureCredential } from "@azure/identity"; // Define Event Hubs Endpoint and related entity name here here -const evenHubsEndpoint = ""; // .servicebus.windows.net -const eventHubName = ""; -const consumerGroup = ""; +const eventHubsFullyQualifiedName = process.env["EVENTHUB_FQDN"] || ""; // .servicebus.windows.net +const eventHubName = process.env["EVENTHUB_NAME"] || ""; +const consumerGroup = process.env["CONSUMER_GROUP_NAME"] || ""; // Define AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET of your AAD application in your environment -async function main(): Promise { +export async function main(): Promise { + console.log(`Running usingAadAuth sample`); + const credential = new DefaultAzureCredential(); - const client = new EventHubConsumerClient(consumerGroup, evenHubsEndpoint, eventHubName, credential); + const client = new EventHubConsumerClient(consumerGroup, eventHubsFullyQualifiedName, eventHubName, credential); /* Refer to other samples, and place your code here to send/receive events */ await client.close(); + + console.log(`Exiting usingAadAuth sample`); } -main().catch((err) => { - console.log("error: ", err); -}); +if (!process.env["RUNNING_IN_TESTS"]) { + main().catch((err) => { + console.log("Error occurred: ", err); + process.exit(1); + }); +} \ No newline at end of file diff --git a/sdk/eventhub/event-hubs/samples/websockets.ts b/sdk/eventhub/event-hubs/samples/websockets.ts index 6337b889dbc1..3c297bdaa51a 100644 --- a/sdk/eventhub/event-hubs/samples/websockets.ts +++ b/sdk/eventhub/event-hubs/samples/websockets.ts @@ -20,9 +20,9 @@ const url = require("url"); const httpsProxyAgent = require("https-proxy-agent"); // Define connection string and related Event Hubs entity name here -const connectionString = ""; -const eventHubName = ""; -const consumerGroup = ""; +const connectionString = process.env["EVENTHUB_CONNECTION_STRING"] || ""; +const eventHubName = process.env["EVENTHUB_NAME"] || ""; +const consumerGroup = process.env["CONSUMER_GROUP_NAME"] || ""; // Create an instance of the `HttpsProxyAgent` class with the proxy server information like // proxy url, username and password @@ -31,7 +31,9 @@ const urlParts = url.parse("http://localhost:3128"); urlParts.auth = "username:password"; // Skip this if proxy server does not need authentication. const proxyAgent = new httpsProxyAgent(urlParts); -async function main(): Promise { +export async function main(): Promise { + console.log(`Running websockets sample`); + const client = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName, { webSocketOptions: { webSocket: WebSocket, @@ -42,8 +44,13 @@ async function main(): Promise { Refer to other samples, and place your code here to send/receive events */ await client.close(); + + console.log(`Exiting websockets sample`); } -main().catch(err => { - console.log("error: ", err); -}); +if (!process.env["RUNNING_IN_TESTS"]) { + main().catch((err) => { + console.log("Error occurred: ", err); + process.exit(1); + }); +} From e35ca31e53ed4f445c2e6fccb829242a46aac8ce Mon Sep 17 00:00:00 2001 From: Richard Park Date: Mon, 9 Dec 2019 13:52:32 -0800 Subject: [PATCH 02/15] Standardizing the boilerplate --- sdk/eventhub/event-hubs/samples/package.json | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json index 8522b8c73286..50c9ec827c8a 100644 --- a/sdk/eventhub/event-hubs/samples/package.json +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -1,5 +1,5 @@ { - "name": "eventhubs-samples", + "name": "event-hubs-samples", "version": "1.0.0", "description": "The samples in this folder are for version 5.0.0 and above of this library. If you are using version 2.1.0 or lower, then please use [samples for v2.1.0](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples) instead", "main": "dist/runsamples.js", @@ -7,9 +7,19 @@ "test": "ts-node ./runsamples.ts", "build": "tsc -p ." }, - "keywords": [], - "author": "", - "license": "ISC", + "keywords": [ + "Azure", + "Storage", + "File", + "Node.js", + "TypeScript" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js#readme", "devDependencies": { "ts-node": "^8.5.4", "typescript": "^3.7.2" From bd454a77d528bf08e9da0168d72a6c230d68eb4f Mon Sep 17 00:00:00 2001 From: Richard Park Date: Mon, 9 Dec 2019 13:55:45 -0800 Subject: [PATCH 03/15] Whoops, missed the azure- --- sdk/eventhub/event-hubs/samples/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json index 50c9ec827c8a..a7a226806e63 100644 --- a/sdk/eventhub/event-hubs/samples/package.json +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -1,5 +1,5 @@ { - "name": "event-hubs-samples", + "name": "azure-event-hubs-samples", "version": "1.0.0", "description": "The samples in this folder are for version 5.0.0 and above of this library. If you are using version 2.1.0 or lower, then please use [samples for v2.1.0](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples) instead", "main": "dist/runsamples.js", From fc47eab79b38b46481364799d549fd1c16e5b18b Mon Sep 17 00:00:00 2001 From: Richard Park Date: Mon, 9 Dec 2019 16:13:12 -0800 Subject: [PATCH 04/15] Make the sendEvents.ts a bit more illustrative of how you'd send multiple events over several batches. --- sdk/eventhub/event-hubs/samples/sendEvents.ts | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/sendEvents.ts b/sdk/eventhub/event-hubs/samples/sendEvents.ts index 60a0e17d1f9d..69f0af52e890 100644 --- a/sdk/eventhub/event-hubs/samples/sendEvents.ts +++ b/sdk/eventhub/event-hubs/samples/sendEvents.ts @@ -21,6 +21,9 @@ export async function main(): Promise { const producer = new EventHubProducerClient(connectionString, eventHubName); console.log("Creating and sending a batch of events..."); + + const eventsToSend = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; + try { // By not specifying a partition ID or a partition key we allow the server to choose // which partition will accept this message. @@ -32,21 +35,40 @@ export async function main(): Promise { // If you would like more control you can pass either a `partitionKey` or a `partitionId` // into the createBatch() `options` parameter which will allow you full control over the // destination. - const batch = await producer.createBatch(); + let batch = await producer.createBatch(); // add events to our batch - for (let index = 0; index < 10; index++) { + for (const event of eventsToSend) { // messages can fail to be added to the batch if they exceed the maximum size configured for // the EventHub. - const isAdded = batch.tryAdd({ body: "Sent along with 9 other events using batch" }); + const isAdded = batch.tryAdd({ body: event }); if (!isAdded) { - console.log(`Unable to add event ${index} to the batch`); - break; + if (batch.count === 0) { + // if we can't add it and the batch is empty that means the message we're trying to send + // is too large, even when it would be the _only_ message in the batch. + // + // To fix this you'll need to potentially split the message up across multiple batches or + // skip it. In this example, we'll skip the message. + console.log(`Message was too large and can't be sent until it's made smaller. Skipping...`); + continue; + } + + // otherwise this just signals a good spot to send our batch + console.log(`Batch is full - sending ${batch.count} messages as a single batch.`) + await producer.sendBatch(batch); + + // and create a new one to house the next set of messages + batch = await producer.createBatch(); + continue; } } - - await producer.sendBatch(batch); + + // send any remaining messages, if any. + if (batch.count > 0) { + console.log(`Sending remaining ${batch.count} messages as a single batch.`) + await producer.sendBatch(batch); + } } catch (err) { console.log("Error when creating & sending a batch of events: ", err); } From b9220422af34dc4d8607f4ce9908487d17fa4df8 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Mon, 9 Dec 2019 16:43:29 -0800 Subject: [PATCH 05/15] Make the tsconfig file standalone (no relative references) --- sdk/eventhub/event-hubs/samples/tsconfig.json | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/tsconfig.json b/sdk/eventhub/event-hubs/samples/tsconfig.json index 9b753039b6f1..6fde1b75b459 100644 --- a/sdk/eventhub/event-hubs/samples/tsconfig.json +++ b/sdk/eventhub/event-hubs/samples/tsconfig.json @@ -1,13 +1,35 @@ { - "extends": "../tsconfig.json", "compilerOptions": { - "module": "commonjs" + /* Basic Options */ + "target": "es2016" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */, + "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, + "declaration": true /* Generates corresponding '.d.ts' file. */, + "declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */, + "sourceMap": true /* Generates corresponding '.map' file. */, + "outDir": "./dist-esm" /* Redirect output structure to the directory. */, + "declarationDir": "./typings" /* Output directory for generated declaration files.*/, + "importHelpers": true /* Import emit helpers from 'tslib'. */, + /* Strict Type-Checking Options */ + "strict": true /* Enable all strict type-checking options. */, + "noImplicitReturns": true /* Report error when not all code paths in function return a value. */, + /* Additional Checks */ + "noUnusedLocals": true /* Report errors on unused locals. */, + /* Module Resolution Options */ + "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, + "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + /* Experimental Options */ + "forceConsistentCasingInFileNames": true, + /* Other options */ + "newLine": "LF" /* Use the specified end of line sequence to be used when emitting files: "crlf" (windows) or "lf" (unix).”*/, + "allowJs": false /* Don't allow JavaScript files to be compiled.*/, + "resolveJsonModule": true }, "include": [ - "**/*.ts" + "*.ts" ], "exclude": [ "../node_modules", "../typings/**" ] -} +} \ No newline at end of file From f19de4271c27bec499c5faa534cbf573d435cdfc Mon Sep 17 00:00:00 2001 From: Richard Park Date: Mon, 9 Dec 2019 16:43:51 -0800 Subject: [PATCH 06/15] Fix silly formatting error --- .../samples/receiveEventsUsingCheckpointStore.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts index ddae3af599a4..7e8f528de896 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts @@ -59,7 +59,7 @@ export async function main() { }; console.log( - `Successfully checkpointed event with sequence number: ${events[events.length - 1].sequenceNumber} from partition: 'partitionContext.partitionId'` + `Successfully checkpointed event with sequence number: ${events[events.length - 1].sequenceNumber} from partition: '${context.partitionId}'` ); }, processError: async (err, context) => { @@ -80,9 +80,6 @@ export async function main() { console.log(`Exiting receiveEventsUsingCheckpointStore sample`); } -if (!process.env["RUNNING_IN_TESTS"]) { - main().catch((err) => { - console.log("Error occurred: ", err); - process.exit(1); - }); -} +import { runSample } from './sampleHelpers'; +runSample(main); + From 775b84460a0aef2e30f94887dfd172b4fea55aec Mon Sep 17 00:00:00 2001 From: Richard Park Date: Mon, 9 Dec 2019 16:45:24 -0800 Subject: [PATCH 07/15] Moving some of the ugliness into a sampleHelpers.ts file to make the sample a bit more readable. * Moved the import and the call to the bottom to make it more obvious which parts are "this is sample stuff" and which parts are "this is the code that you want to use" --- sdk/eventhub/event-hubs/samples/README.md | 6 ++--- sdk/eventhub/event-hubs/samples/package.json | 2 +- .../event-hubs/samples/receiveEvents.ts | 8 ++----- .../event-hubs/samples/sampleHelpers.ts | 22 +++++++++++++++++++ sdk/eventhub/event-hubs/samples/sendEvents.ts | 9 ++------ .../event-hubs/samples/useWithIotHub.ts | 8 ++----- .../event-hubs/samples/usingAadAuth.ts | 8 ++----- sdk/eventhub/event-hubs/samples/websockets.ts | 8 ++----- 8 files changed, 35 insertions(+), 36 deletions(-) create mode 100644 sdk/eventhub/event-hubs/samples/sampleHelpers.ts diff --git a/sdk/eventhub/event-hubs/samples/README.md b/sdk/eventhub/event-hubs/samples/README.md index c81a67a3e5e4..51a4f7c7e89f 100644 --- a/sdk/eventhub/event-hubs/samples/README.md +++ b/sdk/eventhub/event-hubs/samples/README.md @@ -32,12 +32,10 @@ Before running a sample, update it with the connection string and the Event Hub 3. Rename the `sample.env` file to `.env` 4. Open the `.env` file in a text editor and fill in values related to the sample you'd like to run. -5. Run the samples using ts-node: - - For example, to run the `sendEvents.ts` sample: +5. Run the samples: ```bash - npx ts-node sendEvents.ts + npm run samples ``` ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Feventhub%2Fevent-hubs%2Fsamples%2FREADME.png) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json index a7a226806e63..6b2e60714c7c 100644 --- a/sdk/eventhub/event-hubs/samples/package.json +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -4,7 +4,7 @@ "description": "The samples in this folder are for version 5.0.0 and above of this library. If you are using version 2.1.0 or lower, then please use [samples for v2.1.0](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples) instead", "main": "dist/runsamples.js", "scripts": { - "test": "ts-node ./runsamples.ts", + "samples": "ts-node ./runsamples.ts", "build": "tsc -p ." }, "keywords": [ diff --git a/sdk/eventhub/event-hubs/samples/receiveEvents.ts b/sdk/eventhub/event-hubs/samples/receiveEvents.ts index 2fd5d5088a6c..9b344266b639 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEvents.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEvents.ts @@ -51,9 +51,5 @@ export async function main() { console.log(`Exiting receiveEvents sample`); } -if (!process.env["RUNNING_IN_TESTS"]) { - main().catch((err) => { - console.log("Error occurred: ", err); - process.exit(1); - }); -} \ No newline at end of file +import { runSample } from './sampleHelpers'; +runSample(main); \ No newline at end of file diff --git a/sdk/eventhub/event-hubs/samples/sampleHelpers.ts b/sdk/eventhub/event-hubs/samples/sampleHelpers.ts new file mode 100644 index 000000000000..7cc866b3da8c --- /dev/null +++ b/sdk/eventhub/event-hubs/samples/sampleHelpers.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import * as dotenv from "dotenv"; + +// initialize using the .env file in the current folder +dotenv.config(); + +/** + * Runs the async sample function, exiting if needed if it fails. + * @param main The 'main' function for the sample. + */ +export function runSample(main: () => Promise) { + if (!process.env["DO_NOT_EXECUTE_SAMPLE"]) { + return Promise.resolve(); + } + + return main().catch((err) => { + console.log("Error occurred: ", err); + process.exit(1); + }); +} \ No newline at end of file diff --git a/sdk/eventhub/event-hubs/samples/sendEvents.ts b/sdk/eventhub/event-hubs/samples/sendEvents.ts index 69f0af52e890..06da1a61a88f 100644 --- a/sdk/eventhub/event-hubs/samples/sendEvents.ts +++ b/sdk/eventhub/event-hubs/samples/sendEvents.ts @@ -77,10 +77,5 @@ export async function main(): Promise { console.log(`Exiting sendEvents sample`); } -if (!process.env["RUNNING_IN_TESTS"]) { - main().catch((err) => { - console.log("Error occurred: ", err); - process.exit(1); - }); -} - +import { runSample } from './sampleHelpers'; +runSample(main); diff --git a/sdk/eventhub/event-hubs/samples/useWithIotHub.ts b/sdk/eventhub/event-hubs/samples/useWithIotHub.ts index 49821fbce809..9b6888700d01 100644 --- a/sdk/eventhub/event-hubs/samples/useWithIotHub.ts +++ b/sdk/eventhub/event-hubs/samples/useWithIotHub.ts @@ -23,9 +23,5 @@ export async function main(): Promise { console.log(`Exiting useWithIotHub sample`); } -if (!process.env["RUNNING_IN_TESTS"]) { - main().catch((err) => { - console.log("Error occurred: ", err); - process.exit(1); - }); -} +import { runSample } from './sampleHelpers'; +runSample(main); diff --git a/sdk/eventhub/event-hubs/samples/usingAadAuth.ts b/sdk/eventhub/event-hubs/samples/usingAadAuth.ts index db2c83860453..77365af49e65 100644 --- a/sdk/eventhub/event-hubs/samples/usingAadAuth.ts +++ b/sdk/eventhub/event-hubs/samples/usingAadAuth.ts @@ -46,9 +46,5 @@ export async function main(): Promise { console.log(`Exiting usingAadAuth sample`); } -if (!process.env["RUNNING_IN_TESTS"]) { - main().catch((err) => { - console.log("Error occurred: ", err); - process.exit(1); - }); -} \ No newline at end of file +import { runSample } from './sampleHelpers'; +runSample(main); diff --git a/sdk/eventhub/event-hubs/samples/websockets.ts b/sdk/eventhub/event-hubs/samples/websockets.ts index 3c297bdaa51a..47a7d06ce42d 100644 --- a/sdk/eventhub/event-hubs/samples/websockets.ts +++ b/sdk/eventhub/event-hubs/samples/websockets.ts @@ -48,9 +48,5 @@ export async function main(): Promise { console.log(`Exiting websockets sample`); } -if (!process.env["RUNNING_IN_TESTS"]) { - main().catch((err) => { - console.log("Error occurred: ", err); - process.exit(1); - }); -} +import { runSample } from './sampleHelpers'; +runSample(main); From 08c29eddb8ae3247031173f5f4ef09f12701ae28 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Mon, 9 Dec 2019 16:54:15 -0800 Subject: [PATCH 08/15] Whoops, ordering matters. Moving the import back up top to ensure the environment variables get initialized before the sample runs. --- sdk/eventhub/event-hubs/samples/receiveEvents.ts | 2 +- .../event-hubs/samples/receiveEventsUsingCheckpointStore.ts | 2 +- sdk/eventhub/event-hubs/samples/runsamples.ts | 5 +++++ sdk/eventhub/event-hubs/samples/sampleHelpers.ts | 2 +- sdk/eventhub/event-hubs/samples/sendEvents.ts | 2 +- sdk/eventhub/event-hubs/samples/useWithIotHub.ts | 2 +- sdk/eventhub/event-hubs/samples/usingAadAuth.ts | 2 +- sdk/eventhub/event-hubs/samples/websockets.ts | 2 +- 8 files changed, 12 insertions(+), 7 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/receiveEvents.ts b/sdk/eventhub/event-hubs/samples/receiveEvents.ts index 9b344266b639..77f203f3e70e 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEvents.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEvents.ts @@ -12,6 +12,7 @@ https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead. */ +import { runSample } from './sampleHelpers'; import { EventHubConsumerClient } from "@azure/event-hubs"; @@ -51,5 +52,4 @@ export async function main() { console.log(`Exiting receiveEvents sample`); } -import { runSample } from './sampleHelpers'; runSample(main); \ No newline at end of file diff --git a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts index 7e8f528de896..0fdd3b12c85c 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts @@ -16,6 +16,7 @@ https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead. */ +import { runSample } from './sampleHelpers'; import { EventHubConsumerClient, CheckpointStore, } from "@azure/event-hubs"; @@ -80,6 +81,5 @@ export async function main() { console.log(`Exiting receiveEventsUsingCheckpointStore sample`); } -import { runSample } from './sampleHelpers'; runSample(main); diff --git a/sdk/eventhub/event-hubs/samples/runsamples.ts b/sdk/eventhub/event-hubs/samples/runsamples.ts index 128969cdfc99..f89b877f4646 100644 --- a/sdk/eventhub/event-hubs/samples/runsamples.ts +++ b/sdk/eventhub/event-hubs/samples/runsamples.ts @@ -1,6 +1,11 @@ import * as dotenv from "dotenv"; +import process from "process"; + dotenv.config(); +// don't have the samples execute - we'll run them manually in `main` below +process.env["DO_NOT_EXECUTE_SAMPLE"] = "1"; + import { main as sendEventsMain } from "./sendEvents"; import { main as receiveEventsMain } from "./receiveEvents"; import { main as receiveEventsUsingCheckpointStoreMain } from "./receiveEventsUsingCheckpointStore"; diff --git a/sdk/eventhub/event-hubs/samples/sampleHelpers.ts b/sdk/eventhub/event-hubs/samples/sampleHelpers.ts index 7cc866b3da8c..6728669c8123 100644 --- a/sdk/eventhub/event-hubs/samples/sampleHelpers.ts +++ b/sdk/eventhub/event-hubs/samples/sampleHelpers.ts @@ -11,7 +11,7 @@ dotenv.config(); * @param main The 'main' function for the sample. */ export function runSample(main: () => Promise) { - if (!process.env["DO_NOT_EXECUTE_SAMPLE"]) { + if (process.env["DO_NOT_EXECUTE_SAMPLE"]) { return Promise.resolve(); } diff --git a/sdk/eventhub/event-hubs/samples/sendEvents.ts b/sdk/eventhub/event-hubs/samples/sendEvents.ts index 06da1a61a88f..99ffafb8487c 100644 --- a/sdk/eventhub/event-hubs/samples/sendEvents.ts +++ b/sdk/eventhub/event-hubs/samples/sendEvents.ts @@ -9,6 +9,7 @@ https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead. */ +import { runSample } from './sampleHelpers'; import { EventHubProducerClient } from "@azure/event-hubs"; // Define connection string and related Event Hubs entity name here @@ -77,5 +78,4 @@ export async function main(): Promise { console.log(`Exiting sendEvents sample`); } -import { runSample } from './sampleHelpers'; runSample(main); diff --git a/sdk/eventhub/event-hubs/samples/useWithIotHub.ts b/sdk/eventhub/event-hubs/samples/useWithIotHub.ts index 9b6888700d01..184b2c8b3161 100644 --- a/sdk/eventhub/event-hubs/samples/useWithIotHub.ts +++ b/sdk/eventhub/event-hubs/samples/useWithIotHub.ts @@ -4,6 +4,7 @@ This sample demonstrates how to use the EventHubClient with an IotHub instance */ +import { runSample } from './sampleHelpers'; import { EventHubConsumerClient } from "@azure/event-hubs"; // Define IoT Hub Event Hubs-compatible connection string here. @@ -23,5 +24,4 @@ export async function main(): Promise { console.log(`Exiting useWithIotHub sample`); } -import { runSample } from './sampleHelpers'; runSample(main); diff --git a/sdk/eventhub/event-hubs/samples/usingAadAuth.ts b/sdk/eventhub/event-hubs/samples/usingAadAuth.ts index 77365af49e65..0a3650f737c1 100644 --- a/sdk/eventhub/event-hubs/samples/usingAadAuth.ts +++ b/sdk/eventhub/event-hubs/samples/usingAadAuth.ts @@ -22,6 +22,7 @@ Note: If you are using version 2.1.0 or lower of @azure/event-hubs library, then please use the samples at https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead. */ +import { runSample } from './sampleHelpers'; import { EventHubConsumerClient } from "@azure/event-hubs"; import { DefaultAzureCredential } from "@azure/identity"; @@ -46,5 +47,4 @@ export async function main(): Promise { console.log(`Exiting usingAadAuth sample`); } -import { runSample } from './sampleHelpers'; runSample(main); diff --git a/sdk/eventhub/event-hubs/samples/websockets.ts b/sdk/eventhub/event-hubs/samples/websockets.ts index 47a7d06ce42d..3ed73262f86a 100644 --- a/sdk/eventhub/event-hubs/samples/websockets.ts +++ b/sdk/eventhub/event-hubs/samples/websockets.ts @@ -14,6 +14,7 @@ https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead. */ +import { runSample } from './sampleHelpers'; import { EventHubConsumerClient } from "@azure/event-hubs"; import WebSocket from "ws"; const url = require("url"); @@ -48,5 +49,4 @@ export async function main(): Promise { console.log(`Exiting websockets sample`); } -import { runSample } from './sampleHelpers'; runSample(main); From 41de2ca9f9c85a1e1866771136572c5704d6ec30 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Tue, 10 Dec 2019 11:17:37 -0800 Subject: [PATCH 09/15] We never intend to publish this --- sdk/eventhub/event-hubs/samples/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json index 6b2e60714c7c..12ded1d7264f 100644 --- a/sdk/eventhub/event-hubs/samples/package.json +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -1,5 +1,6 @@ { "name": "azure-event-hubs-samples", + "private": true, "version": "1.0.0", "description": "The samples in this folder are for version 5.0.0 and above of this library. If you are using version 2.1.0 or lower, then please use [samples for v2.1.0](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples) instead", "main": "dist/runsamples.js", From 79fe18bc27b0afa007432c64cc9c67146208cbb7 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Tue, 10 Dec 2019 11:18:33 -0800 Subject: [PATCH 10/15] Copyright and remove unneeded import --- sdk/eventhub/event-hubs/samples/runsamples.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sdk/eventhub/event-hubs/samples/runsamples.ts b/sdk/eventhub/event-hubs/samples/runsamples.ts index f89b877f4646..6ca9ecba1a69 100644 --- a/sdk/eventhub/event-hubs/samples/runsamples.ts +++ b/sdk/eventhub/event-hubs/samples/runsamples.ts @@ -1,5 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + import * as dotenv from "dotenv"; -import process from "process"; dotenv.config(); From 2948bd19fe10e7bec8628c31ee07941c31af5c8d Mon Sep 17 00:00:00 2001 From: Richard Park Date: Tue, 10 Dec 2019 11:29:22 -0800 Subject: [PATCH 11/15] * My keywords were totally bogus. Fixing... * Adding in @types/node --- sdk/eventhub/event-hubs/samples/package.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json index 12ded1d7264f..317d67c381a4 100644 --- a/sdk/eventhub/event-hubs/samples/package.json +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -10,8 +10,8 @@ }, "keywords": [ "Azure", - "Storage", - "File", + "EventHubs", + "CheckpointStore", "Node.js", "TypeScript" ], @@ -23,7 +23,8 @@ "homepage": "https://github.com/Azure/azure-sdk-for-js#readme", "devDependencies": { "ts-node": "^8.5.4", - "typescript": "^3.7.2" + "typescript": "^3.7.2", + "@types/node": "^12.12.17" }, "dependencies": { "@azure/core-amqp": "next", From ca66ab08212cbcc6be0e8e40bd1f8ab282376498 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Tue, 10 Dec 2019 11:31:41 -0800 Subject: [PATCH 12/15] Folder for runsamples was incorrect (although it's not really used since we're using ts-node for the running) --- sdk/eventhub/event-hubs/samples/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json index 317d67c381a4..80b90912b04d 100644 --- a/sdk/eventhub/event-hubs/samples/package.json +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -3,7 +3,7 @@ "private": true, "version": "1.0.0", "description": "The samples in this folder are for version 5.0.0 and above of this library. If you are using version 2.1.0 or lower, then please use [samples for v2.1.0](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples) instead", - "main": "dist/runsamples.js", + "main": "dist-esm/runsamples.js", "scripts": { "samples": "ts-node ./runsamples.ts", "build": "tsc -p ." From 2b3f2ca54991755a06b8319735afaf471fd82dab Mon Sep 17 00:00:00 2001 From: Richard Park Date: Tue, 10 Dec 2019 11:40:44 -0800 Subject: [PATCH 13/15] Updated with the proper paths for the node_modules folder --- sdk/eventhub/event-hubs/samples/tsconfig.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/tsconfig.json b/sdk/eventhub/event-hubs/samples/tsconfig.json index 6fde1b75b459..04c0208e238a 100644 --- a/sdk/eventhub/event-hubs/samples/tsconfig.json +++ b/sdk/eventhub/event-hubs/samples/tsconfig.json @@ -29,7 +29,7 @@ "*.ts" ], "exclude": [ - "../node_modules", - "../typings/**" + "./node_modules", + "./typings/**" ] } \ No newline at end of file From 766f2ae3c6d96145251c5473fe0df3e5ef2c2281 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Tue, 10 Dec 2019 13:09:01 -0800 Subject: [PATCH 14/15] Added in missing packages --- sdk/eventhub/event-hubs/samples/package.json | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/sdk/eventhub/event-hubs/samples/package.json b/sdk/eventhub/event-hubs/samples/package.json index 80b90912b04d..4de5e6eb2503 100644 --- a/sdk/eventhub/event-hubs/samples/package.json +++ b/sdk/eventhub/event-hubs/samples/package.json @@ -30,6 +30,12 @@ "@azure/core-amqp": "next", "@azure/event-hubs": "next", "@azure/eventhubs-checkpointstore-blob": "next", - "rhea-promise": "^1.0.0" + "@types/dotenv": "^8.2.0", + "@types/ws": "^6.0.4", + "dotenv": "^8.2.0", + "https-proxy-agent": "^3.0.1", + "rhea-promise": "^1.0.0", + "tslib": "^1.9.3", + "ws": "^7.2.0" } } From 3a0ab7d3f638449db0e49841f30c1e1730ee28c0 Mon Sep 17 00:00:00 2001 From: Richard Park Date: Tue, 10 Dec 2019 13:44:35 -0800 Subject: [PATCH 15/15] Make cleanup more robust --- .../event-hubs/samples/receiveEvents.ts | 10 +++------- .../receiveEventsUsingCheckpointStore.ts | 13 +++++------- .../event-hubs/samples/sampleHelpers.ts | 20 +++++++++++++++++++ 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/sdk/eventhub/event-hubs/samples/receiveEvents.ts b/sdk/eventhub/event-hubs/samples/receiveEvents.ts index 77f203f3e70e..c59593498caf 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEvents.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEvents.ts @@ -12,7 +12,7 @@ https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead. */ -import { runSample } from './sampleHelpers'; +import { runSample, cleanupAfterWaiting } from './sampleHelpers'; import { EventHubConsumerClient } from "@azure/event-hubs"; @@ -40,14 +40,10 @@ export async function main() { } }); - // after 30 seconds, stop processing - await new Promise((resolve) => { - setTimeout(async () => { + await cleanupAfterWaiting(async () => { await subscription.close(); await consumerClient.close(); - resolve(); - }, 30000); - }); + }, 30); console.log(`Exiting receiveEvents sample`); } diff --git a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts index 0fdd3b12c85c..ff93f54de9d3 100644 --- a/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts +++ b/sdk/eventhub/event-hubs/samples/receiveEventsUsingCheckpointStore.ts @@ -16,7 +16,7 @@ https://github.com/Azure/azure-sdk-for-js/tree/%40azure/event-hubs_2.1.0/sdk/eventhub/event-hubs/samples instead. */ -import { runSample } from './sampleHelpers'; +import { runSample, cleanupAfterWaiting } from './sampleHelpers'; import { EventHubConsumerClient, CheckpointStore, } from "@azure/event-hubs"; @@ -70,13 +70,10 @@ export async function main() { ); // after 30 seconds, stop processing - await new Promise((resolve) => { - setTimeout(async () => { - await subscription.close(); - await consumerClient.close(); - resolve(); - }, 30000); - }); + await cleanupAfterWaiting(async () => { + await subscription.close(); + await consumerClient.close(); + }, 30); console.log(`Exiting receiveEventsUsingCheckpointStore sample`); } diff --git a/sdk/eventhub/event-hubs/samples/sampleHelpers.ts b/sdk/eventhub/event-hubs/samples/sampleHelpers.ts index 6728669c8123..026b409979a0 100644 --- a/sdk/eventhub/event-hubs/samples/sampleHelpers.ts +++ b/sdk/eventhub/event-hubs/samples/sampleHelpers.ts @@ -19,4 +19,24 @@ export function runSample(main: () => Promise) { console.log("Error occurred: ", err); process.exit(1); }); +} + +/** + * Runs your cleanupFn after waiting for `timeToWaitInSeconds` seconds + * @param cleanupFn Cleanup function to run. + * @param timeToWaitInSeconds Seconds to wait. + */ +export function cleanupAfterWaiting(cleanupFn: () => Promise, timeToWaitInSeconds: number): Promise { + return new Promise((resolve, reject) => { + console.log(`Waiting for ${timeToWaitInSeconds} seconds...`) + + setTimeout(async () => { + try { + await cleanupFn(); + resolve(); + } catch (err) { + reject(err); + } + }, timeToWaitInSeconds * 1000); + }); } \ No newline at end of file