@azure/eventgrid
Advanced tools
Comparing version 3.0.0-beta.2 to 3.0.0-beta.3
# Release History | ||
## 3.0.0-beta.3 (2020-10-06) | ||
- Added distributed tracing support. `EventGridProducerClient` will now create spans when sending events to Event Grid. | ||
- Added support for system events sent by Azure Key Vault. | ||
### Breaking Changes | ||
- The type definitions for SMS events sent by Azure Communication Services have been renamed, to use the prefix "AcsSms" instead of "Acssms". If you are | ||
using TypeScript and explicitly referencing these interfaces, you will need to update your code to use the new names. The payload of the events is unchanged. | ||
- `EventGridSharedAccessCredential` has been removed, in favor of `AzureSASCredential`. Code which is using `EventGridSharedAccessCredential` should | ||
now use `AzureSASCredential` instead. | ||
- When constructing the client, you must now include the schema type your topic is configured to expect (one of "EventGrid", "CloudEvent" or "Custom"). | ||
- The `sendEvents` methods have been collapsed into a single method on the client called `send` which uses the input schema that was configured on the client. | ||
## 3.0.0-beta.2 (2020-09-24) | ||
@@ -4,0 +18,0 @@ |
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT license. | ||
export const SDK_VERSION = "3.0.0-beta.2"; | ||
export const SDK_VERSION = "3.0.0-beta.3"; | ||
export const DEFAULT_API_VERSION = "2018-01-01"; | ||
//# sourceMappingURL=constants.js.map |
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT license. | ||
import { __awaiter } from "tslib"; | ||
import { Serializer } from "@azure/core-http"; | ||
import { createSerializer } from "@azure/core-client"; | ||
import { cloudEventReservedPropertyNames } from "./models"; | ||
@@ -9,9 +9,9 @@ import { EventGridEvent as EventGridEventMapper, CloudEvent as CloudEventMapper } from "./generated/models/mappers"; | ||
import { systemDeserializers } from "./systemEventDecoders"; | ||
const serializer = new Serializer(); | ||
const serializer = createSerializer(); | ||
/** | ||
* EventGridConsumer is used to aid in processing events delivered by EventGrid. It can deserialize a JSON encoded payload | ||
* EventGridDeserializer is used to aid in processing events delivered by EventGrid. It can deserialize a JSON encoded payload | ||
* of either a single event or batch of events as well as be used to convert the result of `JSON.parse` into an | ||
* `EventGridEvent` or `CloudEvent` like object. | ||
* | ||
* Unlike normal JSON deseralization, EventGridConsumer does some additional conversions: | ||
* Unlike normal JSON deseralization, EventGridDeserializer does some additional conversions: | ||
* | ||
@@ -22,12 +22,4 @@ * - The consumer parses the event time property into a `Date` object, for ease of use. | ||
* - The `data` payload from system events is converted to match the interfaces this library defines. | ||
* | ||
* When constructing an `EventGridConsumer`, a map of event types to custom deserializers may be provided. When | ||
* deserializing, if a custom deserializer has been registered for a given event type, it will be called with the | ||
* data object. The object this deserializer returns will replace the existing data object. | ||
*/ | ||
export class EventGridConsumer { | ||
constructor(options) { | ||
var _a; | ||
this.customDeserializers = (_a = options === null || options === void 0 ? void 0 : options.customDeserializers) !== null && _a !== void 0 ? _a : {}; | ||
} | ||
export class EventGridDeserializer { | ||
deserializeEventGridEvents(encodedEvents) { | ||
@@ -43,5 +35,2 @@ return __awaiter(this, void 0, void 0, function* () { | ||
} | ||
else if (this.customDeserializers[deserialized.eventType]) { | ||
deserialized.data = yield this.customDeserializers[deserialized.eventType](deserialized.data); | ||
} | ||
events.push(deserialized); | ||
@@ -96,5 +85,2 @@ } | ||
} | ||
else if (this.customDeserializers[modelEvent.type]) { | ||
modelEvent.data = yield this.customDeserializers[modelEvent.type](modelEvent.data); | ||
} | ||
// Build the "extensionsAttributes" property bag by removing all known top level properties. | ||
@@ -101,0 +87,0 @@ const extensionAttributes = Object.assign({}, deserialized); |
@@ -7,3 +7,2 @@ // Copyright (c) Microsoft Corporation. | ||
* @internal | ||
* @ignore | ||
*/ | ||
@@ -10,0 +9,0 @@ export function sha256Hmac(secret, stringToSign) { |
@@ -7,3 +7,2 @@ // Copyright (c) Microsoft Corporation. | ||
* @internal | ||
* @ignore | ||
*/ | ||
@@ -10,0 +9,0 @@ export function sha256Hmac(secret, stringToSign) { |
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT license. | ||
import { __awaiter } from "tslib"; | ||
import { BaseRequestPolicy } from "@azure/core-http"; | ||
import { isKeyCredentialLike } from "./util"; | ||
@@ -15,12 +14,5 @@ /** | ||
/** | ||
* Create an HTTP pipeline policy to authenticate a request | ||
* using an `AzureKeyCredential` for Event Grid | ||
* The programmatic identifier of the eventGridCredentialPolicy. | ||
*/ | ||
export function createEventGridCredentialPolicy(credential) { | ||
return { | ||
create: (nextPolicy, options) => { | ||
return new EventGridAzureKeyCredentialPolicy(nextPolicy, options, credential); | ||
} | ||
}; | ||
} | ||
export const eventGridCredentialPolicyName = "eventGridCredentialPolicy"; | ||
/** | ||
@@ -30,22 +22,18 @@ * A concrete implementation of an AzureKeyCredential policy | ||
*/ | ||
class EventGridAzureKeyCredentialPolicy extends BaseRequestPolicy { | ||
constructor(nextPolicy, options, credential) { | ||
super(nextPolicy, options); | ||
this.credential = credential; | ||
} | ||
sendRequest(webResource) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!webResource) { | ||
throw new Error("webResource cannot be null or undefined"); | ||
} | ||
if (isKeyCredentialLike(this.credential)) { | ||
webResource.headers.set(API_KEY_HEADER_NAME, this.credential.key); | ||
} | ||
else { | ||
webResource.headers.set(SAS_TOKEN_HEADER_NAME, this.credential.signature()); | ||
} | ||
return this._nextPolicy.sendRequest(webResource); | ||
}); | ||
} | ||
export function eventGridCredentialPolicy(credential) { | ||
return { | ||
name: eventGridCredentialPolicyName, | ||
sendRequest(request, next) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (isKeyCredentialLike(credential)) { | ||
request.headers.set(API_KEY_HEADER_NAME, credential.key); | ||
} | ||
else { | ||
request.headers.set(SAS_TOKEN_HEADER_NAME, credential.signature); | ||
} | ||
return next(request); | ||
}); | ||
} | ||
}; | ||
} | ||
//# sourceMappingURL=eventGridAuthenticationPolicy.js.map |
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT license. | ||
import { createPipelineFromOptions, generateUuid } from "@azure/core-http"; | ||
import { createEventGridCredentialPolicy } from "./eventGridAuthenticationPolicy"; | ||
import { __awaiter } from "tslib"; | ||
import { createClientPipeline } from "@azure/core-client"; | ||
import { eventGridCredentialPolicy } from "./eventGridAuthenticationPolicy"; | ||
import { SDK_VERSION } from "./constants"; | ||
import { cloudEventReservedPropertyNames } from "./models"; | ||
import { GeneratedClient } from "./generated/generatedClient"; | ||
import { cloudEventDistributedTracingEnricherPolicy } from "./cloudEventDistrubtedTracingEnricherPolicy"; | ||
import { createSpan } from "./tracing"; | ||
import { CanonicalCode } from "@opentelemetry/api"; | ||
import { v4 as uuidv4 } from "uuid"; | ||
/** | ||
@@ -13,3 +18,3 @@ * Client class for publishing events to the Event Grid Service. | ||
/** | ||
* Creates an instance of EventGridPublisherClient. | ||
* Creates an instance of EventGridPublisherClient which sends events using the Event Grid Schema. | ||
* | ||
@@ -22,2 +27,3 @@ * Example usage: | ||
* "<service endpoint>", | ||
* "EventGrid", | ||
* new AzureKeyCredential("<api key>") | ||
@@ -27,8 +33,10 @@ * ); | ||
* | ||
* @param endpointUrl The URL to the EventGrid endpoint, e.g. https://eg-topic.westus2-1.eventgrid.azure.net/api/events | ||
* @param credential Used to authenticate requests to the service. | ||
* @param options Used to configure the Event Grid Client | ||
* @param endpointUrl - The URL to the Event Grid endpoint, e.g. https://eg-topic.westus2-1.eventgrid.azure.net/api/events. | ||
* @param inputSchema - The schema that the Event Grid endpoint is configured to accept. One of "EventGrid", "CloudEvent", or "Custom". | ||
* @param credential - Used to authenticate requests to the service. | ||
* @param options - Used to configure the Event Grid Client. | ||
*/ | ||
constructor(endpointUrl, credential, options = {}) { | ||
constructor(endpointUrl, inputSchema, credential, options = {}) { | ||
this.endpointUrl = endpointUrl; | ||
this.inputSchema = inputSchema; | ||
const libInfo = `azsdk-js-eventgrid/${SDK_VERSION}`; | ||
@@ -45,49 +53,43 @@ const pipelineOptions = Object.assign({}, options); | ||
} | ||
const authPolicy = createEventGridCredentialPolicy(credential); | ||
const pipeline = createPipelineFromOptions(options, authPolicy); | ||
this.client = new GeneratedClient(pipeline); | ||
const pipeline = createClientPipeline(pipelineOptions); | ||
const authPolicy = eventGridCredentialPolicy(credential); | ||
pipeline.addPolicy(authPolicy); | ||
pipeline.addPolicy(cloudEventDistributedTracingEnricherPolicy()); | ||
this.client = new GeneratedClient({ pipeline }); | ||
this.apiVersion = this.client.apiVersion; | ||
} | ||
/** | ||
* Publishes events in the Event Grid scheama. The topic must be configured to expect events in the Event Grid schema. | ||
* Sends events to a topic. | ||
* | ||
* @param message One or more events to publish | ||
* @param events - The events to send. The events should be in the schema used when constructing the client. | ||
* @param options - Options to control the underlying operation. | ||
*/ | ||
sendEvents(events, options) { | ||
return this.client | ||
.publishEvents(this.endpointUrl, (events || []).map(convertEventGridEventToModelType), options) | ||
.then((r) => { | ||
return { | ||
_response: r._response | ||
}; | ||
send(events, options) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const { span, updatedOptions } = createSpan("EventGridPublisherClient-send", options || {}); | ||
try { | ||
switch (this.inputSchema) { | ||
case "EventGrid": { | ||
return yield this.client.publishEvents(this.endpointUrl, events.map(convertEventGridEventToModelType), updatedOptions); | ||
} | ||
case "CloudEvent": { | ||
return yield this.client.publishCloudEventEvents(this.endpointUrl, events.map(convertCloudEventToModelType), updatedOptions); | ||
} | ||
case "Custom": { | ||
return yield this.client.publishCustomEventEvents(this.endpointUrl, events, updatedOptions); | ||
} | ||
default: { | ||
throw new Error(`Unknown input schema type '${this.inputSchema}'`); | ||
} | ||
} | ||
} | ||
catch (e) { | ||
span.setStatus({ code: CanonicalCode.UNKNOWN, message: e.message }); | ||
throw e; | ||
} | ||
finally { | ||
span.end(); | ||
} | ||
}); | ||
} | ||
/** | ||
* Publishes events in the Cloud Events 1.0 schema. The topic must be configured to expect events in the Cloud Events 1.0 schema. | ||
* | ||
* @param message One or more events to publish | ||
*/ | ||
sendCloudEvents(events, options) { | ||
return this.client | ||
.publishCloudEventEvents(this.endpointUrl, (events || []).map(convertCloudEventToModelType), options) | ||
.then((r) => { | ||
return { | ||
_response: r._response | ||
}; | ||
}); | ||
} | ||
/** | ||
* Publishes events written using a custom schema. The topic must be configured to expect events in a custom schema. | ||
* | ||
* @param message One or more events to publish | ||
*/ | ||
sendCustomSchemaEvents(events, options) { | ||
return this.client | ||
.publishCustomEventEvents(this.endpointUrl, events || [], options) | ||
.then((r) => { | ||
return { | ||
_response: r._response | ||
}; | ||
}); | ||
} | ||
} | ||
@@ -102,3 +104,3 @@ /** | ||
eventTime: (_a = event.eventTime) !== null && _a !== void 0 ? _a : new Date(), | ||
id: (_b = event.id) !== null && _b !== void 0 ? _b : generateUuid(), | ||
id: (_b = event.id) !== null && _b !== void 0 ? _b : uuidv4(), | ||
subject: event.subject, | ||
@@ -125,3 +127,3 @@ topic: event.topic, | ||
} | ||
const converted = Object.assign({ specversion: "1.0", type: event.type, source: event.source, id: (_a = event.id) !== null && _a !== void 0 ? _a : generateUuid(), time: (_b = event.time) !== null && _b !== void 0 ? _b : new Date(), subject: event.subject, dataschema: event.dataschema }, ((_c = event.extensionAttributes) !== null && _c !== void 0 ? _c : [])); | ||
const converted = Object.assign({ specversion: "1.0", type: event.type, source: event.source, id: (_a = event.id) !== null && _a !== void 0 ? _a : uuidv4(), time: (_b = event.time) !== null && _b !== void 0 ? _b : new Date(), subject: event.subject, dataschema: event.dataschema }, ((_c = event.extensionAttributes) !== null && _c !== void 0 ? _c : [])); | ||
if (event.data instanceof Uint8Array) { | ||
@@ -128,0 +130,0 @@ if (!event.datacontenttype) { |
@@ -8,8 +8,8 @@ /* | ||
*/ | ||
import * as coreHttp from "@azure/core-http"; | ||
import { createSerializer } from "@azure/core-client"; | ||
import * as Parameters from "./models/parameters"; | ||
import * as Models from "./models"; | ||
import * as Mappers from "./models/mappers"; | ||
import { GeneratedClientContext } from "./generatedClientContext"; | ||
class GeneratedClient extends GeneratedClientContext { | ||
/** @hidden */ | ||
export class GeneratedClient extends GeneratedClientContext { | ||
/** | ||
@@ -29,4 +29,3 @@ * Initializes a new instance of the GeneratedClient class. | ||
publishEvents(topicHostname, events, options) { | ||
const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {}); | ||
return this.sendOperationRequest({ topicHostname, events, options: operationOptions }, publishEventsOperationSpec); | ||
return this.sendOperationRequest({ topicHostname, events, options }, publishEventsOperationSpec); | ||
} | ||
@@ -40,4 +39,3 @@ /** | ||
publishCloudEventEvents(topicHostname, events, options) { | ||
const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {}); | ||
return this.sendOperationRequest({ topicHostname, events, options: operationOptions }, publishCloudEventEventsOperationSpec); | ||
return this.sendOperationRequest({ topicHostname, events, options }, publishCloudEventEventsOperationSpec); | ||
} | ||
@@ -51,10 +49,9 @@ /** | ||
publishCustomEventEvents(topicHostname, events, options) { | ||
const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {}); | ||
return this.sendOperationRequest({ topicHostname, events, options: operationOptions }, publishCustomEventEventsOperationSpec); | ||
return this.sendOperationRequest({ topicHostname, events, options }, publishCustomEventEventsOperationSpec); | ||
} | ||
} | ||
// Operation Specifications | ||
const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); | ||
const serializer = createSerializer(Mappers, /* isXml */ false); | ||
const publishEventsOperationSpec = { | ||
path: "/api/events", | ||
path: "", | ||
httpMethod: "POST", | ||
@@ -70,3 +67,3 @@ responses: { 200: {}, default: {} }, | ||
const publishCloudEventEventsOperationSpec = { | ||
path: "/api/events", | ||
path: "", | ||
httpMethod: "POST", | ||
@@ -82,3 +79,3 @@ responses: { 200: {}, default: {} }, | ||
const publishCustomEventEventsOperationSpec = { | ||
path: "/api/events", | ||
path: "", | ||
httpMethod: "POST", | ||
@@ -93,4 +90,2 @@ responses: { 200: {}, default: {} }, | ||
}; | ||
// Operation Specifications | ||
export { GeneratedClient, GeneratedClientContext, Models as GeneratedModels, Mappers as GeneratedMappers }; | ||
//# sourceMappingURL=generatedClient.js.map |
@@ -8,6 +8,5 @@ /* | ||
*/ | ||
import * as coreHttp from "@azure/core-http"; | ||
const packageName = "@azure/eventgrid"; | ||
const packageVersion = "3.0.0-beta.2"; | ||
export class GeneratedClientContext extends coreHttp.ServiceClient { | ||
import { __rest } from "tslib"; | ||
import { ServiceClient } from "@azure/core-client"; | ||
export class GeneratedClientContext extends ServiceClient { | ||
/** | ||
@@ -17,18 +16,13 @@ * Initializes a new instance of the GeneratedClientContext class. | ||
*/ | ||
constructor(options) { | ||
// Initializing default values for options | ||
if (!options) { | ||
options = {}; | ||
} | ||
if (!options.userAgent) { | ||
const defaultUserAgent = coreHttp.getDefaultUserAgentValue(); | ||
options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`; | ||
} | ||
super(undefined, options); | ||
this.requestContentType = "application/json; charset=utf-8"; | ||
this.baseUri = options.endpoint || "https://{topicHostname}"; | ||
constructor(options = {}) { | ||
const defaults = { | ||
requestContentType: "application/json; charset=utf-8" | ||
}; | ||
const { endpoint, apiVersion } = options, restOptions = __rest(options, ["endpoint", "apiVersion"]); | ||
const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaults), restOptions), { baseUri: endpoint || "{topicHostname}" }); | ||
super(optionsWithDefaults); | ||
// Assigning values to Constant parameters | ||
this.apiVersion = options.apiVersion || "2018-01-01"; | ||
this.apiVersion = apiVersion || "2018-01-01"; | ||
} | ||
} | ||
//# sourceMappingURL=generatedClientContext.js.map |
@@ -8,2 +8,3 @@ /* | ||
*/ | ||
export {}; | ||
//# sourceMappingURL=index.js.map |
@@ -26,3 +26,8 @@ /* | ||
name: "Sequence", | ||
element: { type: { name: "Composite", className: "EventGridEvent" } } | ||
element: { | ||
type: { | ||
name: "Composite", | ||
className: "EventGridEvent" | ||
} | ||
} | ||
} | ||
@@ -71,3 +76,8 @@ } | ||
name: "Sequence", | ||
element: { type: { name: "Composite", className: "CloudEvent" } } | ||
element: { | ||
type: { | ||
name: "Composite", | ||
className: "CloudEvent" | ||
} | ||
} | ||
} | ||
@@ -83,3 +93,7 @@ } | ||
name: "Sequence", | ||
element: { type: { name: "any" } } | ||
element: { | ||
type: { | ||
name: "any" | ||
} | ||
} | ||
} | ||
@@ -86,0 +100,0 @@ } |
@@ -11,6 +11,6 @@ // Copyright (c) Microsoft Corporation. | ||
* | ||
* @param endpointUrl The endpoint for the topic or domain you wish to generate a shared access signature for. | ||
* @param credential The credential to use when generating the shared access signatrue. | ||
* @param expiresOn The time at which the shared access signature is no longer valid. | ||
* @param options Options to control how the signature is generated. | ||
* @param endpointUrl - The endpoint for the topic or domain you wish to generate a shared access signature for. | ||
* @param credential - The credential to use when generating the shared access signatrue. | ||
* @param expiresOn - The time at which the shared access signature is no longer valid. | ||
* @param options - Options to control how the signature is generated. | ||
*/ | ||
@@ -17,0 +17,0 @@ export function generateSharedAccessSignature(endpointUrl, credential, expiresOnUtc, options) { |
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT license. | ||
export { AzureKeyCredential } from "@azure/core-auth"; | ||
export { AzureKeyCredential, AzureSASCredential } from "@azure/core-auth"; | ||
export { EventGridPublisherClient } from "./eventGridClient"; | ||
export { EventGridSharedAccessSignatureCredential } from "./sharedAccessSignitureCredential"; | ||
export { EventGridConsumer } from "./consumer"; | ||
export { EventGridDeserializer } from "./consumer"; | ||
export { generateSharedAccessSignature } from "./generateSharedAccessSignature"; | ||
export { isSystemEvent } from "./predicates"; | ||
//# sourceMappingURL=index.js.map |
@@ -5,5 +5,5 @@ // Copyright (c) Microsoft Corporation. | ||
/** | ||
* The @azure/logger configuration for this package. | ||
* The \@azure/logger configuration for this package. | ||
*/ | ||
export const logger = createClientLogger("eventgrid"); | ||
//# sourceMappingURL=logger.js.map |
@@ -6,3 +6,3 @@ // Copyright (c) Microsoft Corporation. | ||
* | ||
* @param o Either an EventGrid our CloudEvent event. | ||
* @param o - Either an EventGrid our CloudEvent event. | ||
*/ | ||
@@ -9,0 +9,0 @@ function isCloudEventLike(o) { |
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT license. | ||
import { __awaiter } from "tslib"; | ||
import { Serializer } from "@azure/core-http"; | ||
import { ACSChatMessageReceivedEventData, ACSChatMessageEditedEventData, ACSChatMessageDeletedEventData, ACSChatThreadCreatedWithUserEventData, ACSChatThreadWithUserDeletedEventData, ACSChatThreadPropertiesUpdatedPerUserEventData, ACSChatMemberAddedToThreadWithUserEventData, ACSChatMemberRemovedFromThreadWithUserEventData, AcssmsDeliveryReportReceivedEventData, AcssmsReceivedEventData, ACSChatMessageEventBase, ACSChatEventBase, ACSChatThreadMember, AcssmsEventBase, AcssmsDeliveryAttempt, AppConfigurationKeyValueDeletedEventData, AppConfigurationKeyValueModifiedEventData, AppEventTypeDetail, AppServicePlanEventTypeDetail, ContainerRegistryArtifactEventData, ContainerRegistryArtifactEventTarget, ContainerRegistryChartDeletedEventData, ContainerRegistryChartPushedEventData, ContainerRegistryEventActor, ContainerRegistryEventData, ContainerRegistryEventRequest, ContainerRegistryEventSource, ContainerRegistryEventTarget, ContainerRegistryImageDeletedEventData, ContainerRegistryImagePushedEventData, DeviceConnectionStateEventInfo, DeviceConnectionStateEventProperties, DeviceLifeCycleEventProperties, DeviceTelemetryEventProperties, DeviceTwinInfo, DeviceTwinInfoProperties, DeviceTwinInfoX509Thumbprint, DeviceTwinMetadata, DeviceTwinProperties, EventHubCaptureFileCreatedEventData, IotHubDeviceConnectedEventData, IotHubDeviceCreatedEventData, IotHubDeviceDeletedEventData, IotHubDeviceDisconnectedEventData, IotHubDeviceTelemetryEventData, KeyVaultCertificateExpiredEventData, KeyVaultCertificateNearExpiryEventData, KeyVaultCertificateNewVersionCreatedEventData, KeyVaultKeyExpiredEventData, KeyVaultKeyNearExpiryEventData, KeyVaultKeyNewVersionCreatedEventData, KeyVaultSecretExpiredEventData, KeyVaultSecretNearExpiryEventData, KeyVaultSecretNewVersionCreatedEventData, MachineLearningServicesDatasetDriftDetectedEventData, MachineLearningServicesModelDeployedEventData, MachineLearningServicesModelRegisteredEventData, MachineLearningServicesRunCompletedEventData, MachineLearningServicesRunStatusChangedEventData, MapsGeofenceEnteredEventData, MapsGeofenceEventProperties, MapsGeofenceExitedEventData, MapsGeofenceGeometry, MapsGeofenceResultEventData, MediaJobCanceledEventData, MediaJobCancelingEventData, MediaJobError, MediaJobErrorDetail, MediaJobErroredEventData, MediaJobFinishedEventData, MediaJobOutput, MediaJobOutputAsset, MediaJobOutputCanceledEventData, MediaJobOutputCancelingEventData, MediaJobOutputErroredEventData, MediaJobOutputFinishedEventData, MediaJobOutputProcessingEventData, MediaJobOutputProgressEventData, MediaJobOutputScheduledEventData, MediaJobOutputStateChangeEventData, MediaJobProcessingEventData, MediaJobScheduledEventData, MediaJobStateChangeEventData, MediaLiveEventConnectionRejectedEventData, MediaLiveEventEncoderConnectedEventData, MediaLiveEventEncoderDisconnectedEventData, MediaLiveEventIncomingDataChunkDroppedEventData, MediaLiveEventIncomingStreamReceivedEventData, MediaLiveEventIncomingStreamsOutOfSyncEventData, MediaLiveEventIncomingVideoStreamsOutOfSyncEventData, MediaLiveEventIngestHeartbeatEventData, MediaLiveEventTrackDiscontinuityDetectedEventData, RedisExportRDBCompletedEventData, RedisImportRDBCompletedEventData, RedisPatchingCompletedEventData, RedisScalingCompletedEventData, ResourceActionCancelEventData, ResourceActionFailureEventData, ResourceActionSuccessEventData, ResourceDeleteCancelEventData, ResourceDeleteFailureEventData, ResourceDeleteSuccessEventData, ResourceWriteCancelEventData, ResourceWriteFailureEventData, ResourceWriteSuccessEventData, ServiceBusActiveMessagesAvailableWithNoListenersEventData, ServiceBusDeadletterMessagesAvailableWithNoListenersEventData, SignalRServiceClientConnectionConnectedEventData, SignalRServiceClientConnectionDisconnectedEventData, StorageBlobCreatedEventData, StorageBlobDeletedEventData, StorageBlobRenamedEventData, StorageDirectoryCreatedEventData, StorageDirectoryDeletedEventData, StorageDirectoryRenamedEventData, StorageLifecyclePolicyActionSummaryDetail, StorageLifecyclePolicyCompletedEventData, SubscriptionDeletedEventData, SubscriptionValidationEventData, SubscriptionValidationResponse, WebAppServicePlanUpdatedEventData, WebAppServicePlanUpdatedEventDataSku, WebAppUpdatedEventData, WebBackupOperationCompletedEventData, WebBackupOperationFailedEventData, WebBackupOperationStartedEventData, WebRestoreOperationCompletedEventData, WebRestoreOperationFailedEventData, WebRestoreOperationStartedEventData, WebSlotSwapCompletedEventData, WebSlotSwapFailedEventData, WebSlotSwapStartedEventData, WebSlotSwapWithPreviewCancelledEventData, WebSlotSwapWithPreviewStartedEventData } from "./generated/models/mappers"; | ||
const serializer = new Serializer({ | ||
import { createSerializer } from "@azure/core-client"; | ||
import { ACSChatMessageReceivedEventData, ACSChatMessageEditedEventData, ACSChatMessageDeletedEventData, ACSChatThreadCreatedWithUserEventData, ACSChatThreadWithUserDeletedEventData, ACSChatThreadPropertiesUpdatedPerUserEventData, ACSChatMemberAddedToThreadWithUserEventData, ACSChatMemberRemovedFromThreadWithUserEventData, AcsSmsDeliveryReportReceivedEventData, AcsSmsReceivedEventData, ACSChatMessageEventBase, ACSChatEventBase, ACSChatThreadMember, AcsSmsEventBase, AcsSmsDeliveryAttempt, AppConfigurationKeyValueDeletedEventData, AppConfigurationKeyValueModifiedEventData, AppEventTypeDetail, AppServicePlanEventTypeDetail, ContainerRegistryArtifactEventData, ContainerRegistryArtifactEventTarget, ContainerRegistryChartDeletedEventData, ContainerRegistryChartPushedEventData, ContainerRegistryEventActor, ContainerRegistryEventData, ContainerRegistryEventRequest, ContainerRegistryEventSource, ContainerRegistryEventTarget, ContainerRegistryImageDeletedEventData, ContainerRegistryImagePushedEventData, DeviceConnectionStateEventInfo, DeviceConnectionStateEventProperties, DeviceLifeCycleEventProperties, DeviceTelemetryEventProperties, DeviceTwinInfo, DeviceTwinInfoProperties, DeviceTwinInfoX509Thumbprint, DeviceTwinMetadata, DeviceTwinProperties, EventHubCaptureFileCreatedEventData, IotHubDeviceConnectedEventData, IotHubDeviceCreatedEventData, IotHubDeviceDeletedEventData, IotHubDeviceDisconnectedEventData, IotHubDeviceTelemetryEventData, KeyVaultCertificateExpiredEventData, KeyVaultCertificateNearExpiryEventData, KeyVaultCertificateNewVersionCreatedEventData, KeyVaultKeyExpiredEventData, KeyVaultKeyNearExpiryEventData, KeyVaultKeyNewVersionCreatedEventData, KeyVaultSecretExpiredEventData, KeyVaultSecretNearExpiryEventData, KeyVaultSecretNewVersionCreatedEventData, KeyVaultAccessPolicyChangedEventData, MachineLearningServicesDatasetDriftDetectedEventData, MachineLearningServicesModelDeployedEventData, MachineLearningServicesModelRegisteredEventData, MachineLearningServicesRunCompletedEventData, MachineLearningServicesRunStatusChangedEventData, MapsGeofenceEnteredEventData, MapsGeofenceEventProperties, MapsGeofenceExitedEventData, MapsGeofenceGeometry, MapsGeofenceResultEventData, MediaJobCanceledEventData, MediaJobCancelingEventData, MediaJobError, MediaJobErrorDetail, MediaJobErroredEventData, MediaJobFinishedEventData, MediaJobOutput, MediaJobOutputAsset, MediaJobOutputCanceledEventData, MediaJobOutputCancelingEventData, MediaJobOutputErroredEventData, MediaJobOutputFinishedEventData, MediaJobOutputProcessingEventData, MediaJobOutputProgressEventData, MediaJobOutputScheduledEventData, MediaJobOutputStateChangeEventData, MediaJobProcessingEventData, MediaJobScheduledEventData, MediaJobStateChangeEventData, MediaLiveEventConnectionRejectedEventData, MediaLiveEventEncoderConnectedEventData, MediaLiveEventEncoderDisconnectedEventData, MediaLiveEventIncomingDataChunkDroppedEventData, MediaLiveEventIncomingStreamReceivedEventData, MediaLiveEventIncomingStreamsOutOfSyncEventData, MediaLiveEventIncomingVideoStreamsOutOfSyncEventData, MediaLiveEventIngestHeartbeatEventData, MediaLiveEventTrackDiscontinuityDetectedEventData, RedisExportRDBCompletedEventData, RedisImportRDBCompletedEventData, RedisPatchingCompletedEventData, RedisScalingCompletedEventData, ResourceActionCancelEventData, ResourceActionFailureEventData, ResourceActionSuccessEventData, ResourceDeleteCancelEventData, ResourceDeleteFailureEventData, ResourceDeleteSuccessEventData, ResourceWriteCancelEventData, ResourceWriteFailureEventData, ResourceWriteSuccessEventData, ServiceBusActiveMessagesAvailableWithNoListenersEventData, ServiceBusDeadletterMessagesAvailableWithNoListenersEventData, SignalRServiceClientConnectionConnectedEventData, SignalRServiceClientConnectionDisconnectedEventData, StorageBlobCreatedEventData, StorageBlobDeletedEventData, StorageBlobRenamedEventData, StorageDirectoryCreatedEventData, StorageDirectoryDeletedEventData, StorageDirectoryRenamedEventData, StorageLifecyclePolicyActionSummaryDetail, StorageLifecyclePolicyCompletedEventData, SubscriptionDeletedEventData, SubscriptionValidationEventData, SubscriptionValidationResponse, WebAppServicePlanUpdatedEventData, WebAppServicePlanUpdatedEventDataSku, WebAppUpdatedEventData, WebBackupOperationCompletedEventData, WebBackupOperationFailedEventData, WebBackupOperationStartedEventData, WebRestoreOperationCompletedEventData, WebRestoreOperationFailedEventData, WebRestoreOperationStartedEventData, WebSlotSwapCompletedEventData, WebSlotSwapFailedEventData, WebSlotSwapStartedEventData, WebSlotSwapWithPreviewCancelledEventData, WebSlotSwapWithPreviewStartedEventData } from "./generated/models/mappers"; | ||
const serializer = createSerializer({ | ||
ACSChatMessageReceivedEventData: ACSChatMessageReceivedEventData, | ||
@@ -15,9 +15,9 @@ ACSChatMessageEditedEventData: ACSChatMessageEditedEventData, | ||
ACSChatMemberRemovedFromThreadWithUserEventData: ACSChatMemberRemovedFromThreadWithUserEventData, | ||
AcssmsDeliveryReportReceivedEventData: AcssmsDeliveryReportReceivedEventData, | ||
AcssmsReceivedEventData: AcssmsReceivedEventData, | ||
AcssmsDeliveryReportReceivedEventData: AcsSmsDeliveryReportReceivedEventData, | ||
AcssmsReceivedEventData: AcsSmsReceivedEventData, | ||
ACSChatMessageEventBase: ACSChatMessageEventBase, | ||
ACSChatEventBase: ACSChatEventBase, | ||
ACSChatThreadMember: ACSChatThreadMember, | ||
AcssmsEventBase: AcssmsEventBase, | ||
AcssmsDeliveryAttempt: AcssmsDeliveryAttempt, | ||
AcssmsEventBase: AcsSmsEventBase, | ||
AcssmsDeliveryAttempt: AcsSmsDeliveryAttempt, | ||
AppConfigurationKeyValueDeletedEventData: AppConfigurationKeyValueDeletedEventData, | ||
@@ -178,4 +178,4 @@ AppConfigurationKeyValueModifiedEventData: AppConfigurationKeyValueModifiedEventData, | ||
"Microsoft.Communication.ChatMemberRemovedFromThreadWithUser": makeDeserializerFromMapper(ACSChatMemberRemovedFromThreadWithUserEventData), | ||
"Microsoft.Communication.SMSDeliveryReportReceived": makeDeserializerFromMapper(AcssmsDeliveryReportReceivedEventData), | ||
"Microsoft.Communication.SMSReceived": makeDeserializerFromMapper(AcssmsReceivedEventData), | ||
"Microsoft.Communication.SMSDeliveryReportReceived": makeDeserializerFromMapper(AcsSmsDeliveryReportReceivedEventData), | ||
"Microsoft.Communication.SMSReceived": makeDeserializerFromMapper(AcsSmsReceivedEventData), | ||
"Microsoft.ContainerRegistry.ChartDeleted": makeDeserializerFromMapper(ContainerRegistryEventData, [jsonParseDeserializer]), | ||
@@ -193,2 +193,12 @@ "Microsoft.ContainerRegistry.ChartPushed": makeDeserializerFromMapper(ContainerRegistryEventData, [jsonParseDeserializer]), | ||
"Microsoft.EventHub.CaptureFileCreated": makeDeserializerFromMapper(EventHubCaptureFileCreatedEventData), | ||
"Microsoft.KeyVault.CertificateNewVersionCreated": makeDeserializerFromMapper(KeyVaultCertificateNewVersionCreatedEventData), | ||
"Microsoft.KeyVault.CertificateNearExpiry": makeDeserializerFromMapper(KeyVaultCertificateNearExpiryEventData), | ||
"Microsoft.KeyVault.CertificateExpired": makeDeserializerFromMapper(KeyVaultCertificateExpiredEventData), | ||
"Microsoft.KeyVault.KeyNewVersionCreated": makeDeserializerFromMapper(KeyVaultKeyNewVersionCreatedEventData), | ||
"Microsoft.KeyVault.KeyNearExpiry": makeDeserializerFromMapper(KeyVaultKeyNearExpiryEventData), | ||
"Microsoft.KeyVault.KeyExpired": makeDeserializerFromMapper(KeyVaultKeyExpiredEventData), | ||
"Microsoft.KeyVault.SecretNewVersionCreated": makeDeserializerFromMapper(KeyVaultSecretNewVersionCreatedEventData), | ||
"Microsoft.KeyVault.SecretNearExpiry": makeDeserializerFromMapper(KeyVaultSecretNearExpiryEventData), | ||
"Microsoft.KeyVault.SecretExpired": makeDeserializerFromMapper(KeyVaultSecretExpiredEventData), | ||
"Microsoft.KeyVault.VaultAccessPolicyChanged": makeDeserializerFromMapper(KeyVaultAccessPolicyChangedEventData), | ||
"Microsoft.MachineLearningServices.DatasetDriftDetected": makeDeserializerFromMapper(MachineLearningServicesDatasetDriftDetectedEventData), | ||
@@ -195,0 +205,0 @@ "Microsoft.MachineLearningServices.ModelDeployed": makeDeserializerFromMapper(MachineLearningServicesModelDeployedEventData), |
@@ -14,3 +14,3 @@ // Copyright (c) Microsoft Corporation. | ||
* | ||
* @param d The Date object to convert to a string. | ||
* @param d - The Date object to convert to a string. | ||
*/ | ||
@@ -37,6 +37,7 @@ export function dateToServiceTimeString(d) { | ||
* | ||
* @param credential the object to test | ||
* @param credential - The object to test | ||
*/ | ||
export function isKeyCredentialLike(o) { | ||
return o.key !== undefined; | ||
const castO = o; | ||
return castO.key !== undefined; | ||
} | ||
@@ -65,2 +66,3 @@ export function parseAndWrap(jsonStringOrObject) { | ||
} | ||
const castO = o; | ||
validateRequiredStringProperties(o, [ | ||
@@ -76,3 +78,3 @@ "eventType", | ||
validateRequiredAnyProperties(o, ["data"]); | ||
if (o.metadataVersion !== EVENT_GRID_SCHEMA_METADATA_VERSION) { | ||
if (castO.metadataVersion !== EVENT_GRID_SCHEMA_METADATA_VERSION) { | ||
throw new TypeError("event is not in the Event Grid schema"); | ||
@@ -88,3 +90,4 @@ } | ||
} | ||
if (o.specversion !== CLOUD_EVENT_1_0_SPEC_VERSION) { | ||
const castO = o; | ||
if (castO.specversion !== CLOUD_EVENT_1_0_SPEC_VERSION) { | ||
throw new Error("event is not in the Cloud Event 1.0 schema"); | ||
@@ -91,0 +94,0 @@ } |
@@ -6,3 +6,3 @@ { | ||
"description": "An isomorphic client library for the Azure Event Grid service.", | ||
"version": "3.0.0-beta.2", | ||
"version": "3.0.0-beta.3", | ||
"keywords": [ | ||
@@ -13,16 +13,17 @@ "node", | ||
"browser", | ||
"isomorphic" | ||
"isomorphic", | ||
"cloud" | ||
], | ||
"license": "MIT", | ||
"main": "./dist/src/index.js", | ||
"main": "./dist/index.js", | ||
"module": "./dist-esm/src/index.js", | ||
"types": "./types/eventgrid.d.ts", | ||
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/Azure/azure-sdk-for-js.git" | ||
}, | ||
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/eventgrid/eventgrid/README.md", | ||
"repository": "github:Azure/azure-sdk-for-js", | ||
"bugs": { | ||
"url": "https://github.com/Azure/azure-sdk-for-js/issues" | ||
}, | ||
"engines": { | ||
"node": ">=8.0.0" | ||
}, | ||
"files": [ | ||
@@ -55,3 +56,3 @@ "dist/", | ||
"build:node": "tsc -p . && cross-env ONLY_NODE=true rollup -c 2>&1", | ||
"build:samples": "node ../../../common/scripts/prep-samples.js && cd samples && tsc -p .", | ||
"build:samples": "dev-tool samples prep && cd dist-samples && tsc -p .", | ||
"build:test": "tsc -p . && rollup -c rollup.test.config.js 2>&1", | ||
@@ -69,4 +70,4 @@ "build": "tsc -p . && rollup -c 2>&1 && api-extractor run --local", | ||
"integration-test": "npm run integration-test:node && npm run integration-test:browser", | ||
"lint:fix": "eslint \"src/**/*.ts\" --fix --fix-type [problem,suggestion]", | ||
"lint": "eslint src --ext .ts -f html -o textAnalytics-lintReport.html", | ||
"lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", | ||
"lint": "eslint package.json api-extractor.json src test --ext .ts", | ||
"pack": "npm pack 2>&1", | ||
@@ -79,3 +80,4 @@ "prebuild": "npm run clean", | ||
"unit-test:node": "mocha --require source-map-support/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace dist-test/index.node.js", | ||
"unit-test": "npm run unit-test:node && npm run unit-test:browser" | ||
"unit-test": "npm run unit-test:node && npm run unit-test:browser", | ||
"docs": "typedoc --excludePrivate --excludeNotExported --excludeExternals --stripInternal --mode file --out ./dist/docs ./src" | ||
}, | ||
@@ -85,11 +87,15 @@ "sideEffects": false, | ||
"dependencies": { | ||
"@azure/core-auth": "^1.1.3", | ||
"@azure/core-http": "^1.1.6", | ||
"@azure/core-auth": "^1.2.0", | ||
"@azure/core-client": "1.0.0-beta.1", | ||
"@azure/core-https": "1.0.0-beta.1", | ||
"@azure/core-tracing": "1.0.0-preview.9", | ||
"@azure/logger": "^1.0.0", | ||
"@opentelemetry/api": "^0.10.2", | ||
"tslib": "^2.0.0" | ||
"tslib": "^2.0.0", | ||
"uuid": "^8.3.0" | ||
}, | ||
"devDependencies": { | ||
"@azure/dev-tool": "^1.0.0", | ||
"@azure/eslint-plugin-azure-sdk": "^3.0.0", | ||
"@azure/service-bus": "^7.0.0", | ||
"@azure/test-utils-recorder": "^1.0.0", | ||
@@ -108,4 +114,2 @@ "@microsoft/api-extractor": "7.7.11", | ||
"@types/uuid": "^8.0.0", | ||
"@typescript-eslint/eslint-plugin": "^2.0.0", | ||
"@typescript-eslint/parser": "^2.0.0", | ||
"chai": "^4.2.0", | ||
@@ -115,7 +119,3 @@ "chai-as-promised": "^7.1.1", | ||
"dotenv": "^8.2.0", | ||
"eslint": "^6.1.0", | ||
"eslint-config-prettier": "^6.0.0", | ||
"eslint-plugin-no-null": "^1.0.2", | ||
"eslint-plugin-no-only-tests": "^2.3.0", | ||
"eslint-plugin-promise": "^4.1.1", | ||
"eslint": "^7.15.0", | ||
"karma": "^5.1.0", | ||
@@ -133,3 +133,3 @@ "karma-chrome-launcher": "^3.0.0", | ||
"karma-mocha-reporter": "^2.2.5", | ||
"karma-remap-istanbul": "^0.6.0", | ||
"karma-sourcemap-loader": "^0.3.8", | ||
"mocha": "^7.1.1", | ||
@@ -148,4 +148,5 @@ "mocha-junit-reporter": "^1.18.0", | ||
"ts-node": "^8.3.0", | ||
"typescript": "~3.9.3" | ||
"typescript": "4.1.2", | ||
"typedoc": "0.15.2" | ||
} | ||
} |
104
README.md
@@ -12,3 +12,3 @@ # Azure Event Grid client library for JavaScript | ||
[Source code](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventgrid/eventgrid/) | | ||
[Package (NPM)](https://www.npmjs.com/package/@azure/eventgrid) | | ||
[Package (NPM)](https://www.npmjs.com/package/@azure/eventgrid/v/next) | | ||
[API reference documentation](https://aka.ms/azsdk-js-eventgrid-ref-docs) | | ||
@@ -79,3 +79,7 @@ [Product documentation](https://docs.microsoft.com/azure/event-grid/) | | ||
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<Access Key>")); | ||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
"<endpoint schema>", | ||
new AzureKeyCredential("<Access Key>") | ||
); | ||
``` | ||
@@ -85,13 +89,11 @@ | ||
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: | ||
Like an access key, a SAS token allows access to sending events to an Event Grid topic. Unlike an access key, which can be used until it is regenerated, a SAS token has an experation time, at which point it is no longer valid. To use a SAS token for authentication, use the `AzureSASCredential` as follows: | ||
```js | ||
const { | ||
EventGridPublisherClient, | ||
EventGridSharedAccessSignatureCredential | ||
} = require("@azure/eventgrid"); | ||
const { EventGridPublisherClient, AzureSASCredential } = require("@azure/eventgrid"); | ||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
new EventGridSharedAccessSignatureCredential("<SAS Token>") | ||
"<endpoint schema>", | ||
new AzureSASCredential("<SAS Token>") | ||
); | ||
@@ -121,28 +123,58 @@ ``` | ||
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: | ||
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. When you construct the EventGridPublisherClient you must specify which schema your topic is configured to use: | ||
| Schema | Publishing Method | | ||
| ------------ | --------------------- | | ||
| Event Grid | `publishEvents` | | ||
| Cloud Events | `publishCloudEvents` | | ||
| Custom | `publishCustomEvents` | | ||
If your topic is configured to use the Event Grid Schema, set "EventGrid" as the schema type: | ||
Using the wrong method will result in an error from the service and your events will not be published. | ||
```js | ||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
"EventGrid", | ||
new AzureKeyCredential("<API Key>") | ||
); | ||
``` | ||
### EventGridConsumer | ||
If your topic is configured to use the Cloud Event Schema, set "CloudEvent" as the schema type: | ||
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`. | ||
```js | ||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
"CloudEvent", | ||
new AzureKeyCredential("<API Key>") | ||
); | ||
``` | ||
Compared with using `JSON.parse` directly, `EventGridConsumer` does some additional conversions while deserializng events: | ||
If your topic is configured to use a Custom Event Schema, set "Custom" as the schema type: | ||
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. | ||
```js | ||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
"Custom", | ||
new AzureKeyCredential("<API Key>") | ||
); | ||
``` | ||
When creating an instance of `EventGridConsumer` you may supply custom deserializers that are used to further convert the `data` object. | ||
Constructing the client with a different schema than what the topic is configured to expect will result in an error from the service and your events will not be published. | ||
You can see what input schema has been configured for an Event Grid topic by using the [Azure CLI][azure_cli] snippet below: | ||
```bash | ||
az eventgrid topic show --name <your-resource-name> --resource-group <your-resource-group-name> --query "inputSchema" | ||
``` | ||
### EventGridDeserializer | ||
Events delivered to consumers by Event Grid are delivered as JSON. Depending on the type of consumer being delivered to, the Event Grid service may deliver one or more events as part of a single payload. While these events may be deserialized using normal JavaScript methods like `JSON.parse`, this library offers a helper type for deserializing events, called `EventGridDeserializer`. | ||
Compared with using `JSON.parse` directly, `EventGridDeserializer` does some additional conversions while deserializng events: | ||
1. `EventGridDeserializer` validates that the required properties of an event are present and are the right types. | ||
2. `EventGridDeserializer` converts the event time property into a JavaScript `Date` object. | ||
3. When using Cloud Events, binary data may be used for an event's data property (by using `Uint8Array`). When the event is sent through Event Grid, it is encoded in Base 64. `EventGridDeserializer` will decode this data back into an instance of `Uint8Array`. | ||
4. When deserilizing a _System Event_ (an event generated by another Azure service), `EventGridDeserializer` will do additional conversions so that the `data` object matches the corresponding interface which describes its data. When using TypeScript, these interfaces ensure you have strong typing when access properties of the data object for a system event. | ||
When creating an instance of `EventGridDeserializer` you may supply custom deserializers that are used to further convert the `data` object. | ||
## Examples | ||
### Publish a Custom Event to an Event Grid Topic | ||
### Publish a Custom Event to an Event Grid Topic using the Event Grid Schema | ||
@@ -152,5 +184,9 @@ ```js | ||
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>")); | ||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
"EventGrid", | ||
new AzureKeyCredential("<API key>") | ||
); | ||
await client.sendEvents([ | ||
await client.send([ | ||
{ | ||
@@ -167,3 +203,3 @@ eventType: "Azure.Sdk.SampleEvent", | ||
### Publish a Custom Event to a Topic in an Event Grid Domain | ||
### Publish a Custom Event to a Topic in an Event Grid Domain using the Event Grid Schema | ||
@@ -175,5 +211,9 @@ Publishing events to an Event Grid Domain is similar to publish to an Event Grid Topic, except that when using the Event Grid schema for events, you must include the `topic` property. When publishing events in the Cloud Events 1.0 schema, the required `source` property is used as the name of the topic in the domain to publish to: | ||
const client = new EventGridPublisherClient("<endpoint>", new AzureKeyCredential("<API key>")); | ||
const client = new EventGridPublisherClient( | ||
"<endpoint>", | ||
"EventGrid", | ||
new AzureKeyCredential("<API key>") | ||
); | ||
await client.sendEvents([ | ||
await client.send([ | ||
{ | ||
@@ -193,3 +233,3 @@ topic: "my-sample-topic", | ||
`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. | ||
`EventGridDeserializer` can be used to deserialize events delivered by Event Grid. When deserializing an event, you need to know the schema used to deliver the event. In this example we have events being delivered to an Azure Service Bus 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 `EventGridDeserializer` and use `isSystemEvent` to detect what type of events they are. | ||
@@ -199,3 +239,3 @@ ```js | ||
const { DefaultAzureCredential } = require("@azure/identity"); | ||
const { EventGridConsumer, isSystemEvent } = require("@azure/eventgrid"); | ||
const { EventGridDeserializer, isSystemEvent } = require("@azure/eventgrid"); | ||
@@ -206,3 +246,3 @@ const client = new ServiceBusClient("<service bus hostname>", new DefaultAzureCredential()); | ||
const consumer = new EventGridConsumer(); | ||
const consumer = new EventGridDeserializer(); | ||
@@ -209,0 +249,0 @@ async function processMessage(message) { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
1303005
49
49
301
8
14947
1
+ Addeduuid@^8.3.0
+ Added@azure/core-client@1.0.0-beta.1(transitive)
+ Added@azure/core-https@1.0.0-beta.1(transitive)
+ Addedagent-base@6.0.2(transitive)
+ Addeddebug@4.4.0(transitive)
+ Addedhttps-proxy-agent@5.0.1(transitive)
+ Addedms@2.1.3(transitive)
- Removed@azure/core-http@^1.1.6
- Removed@azure/core-asynciterator-polyfill@1.0.2(transitive)
- Removed@azure/core-http@1.2.6(transitive)
- Removed@types/node@22.13.9(transitive)
- Removed@types/node-fetch@2.6.12(transitive)
- Removed@types/tunnel@0.0.1(transitive)
- Removedform-data@4.0.2(transitive)
- Removednode-fetch@2.7.0(transitive)
- Removedprocess@0.11.10(transitive)
- Removedpsl@1.15.0(transitive)
- Removedpunycode@2.3.1(transitive)
- Removedquerystringify@2.2.0(transitive)
- Removedrequires-port@1.0.0(transitive)
- Removedsax@1.4.1(transitive)
- Removedtough-cookie@4.1.4(transitive)
- Removedtr46@0.0.3(transitive)
- Removedtunnel@0.0.6(transitive)
- Removedundici-types@6.20.0(transitive)
- Removeduniversalify@0.2.0(transitive)
- Removedurl-parse@1.5.10(transitive)
- Removedwebidl-conversions@3.0.1(transitive)
- Removedwhatwg-url@5.0.0(transitive)
- Removedxml2js@0.4.23(transitive)
- Removedxmlbuilder@11.0.1(transitive)
Updated@azure/core-auth@^1.2.0