From f8f19dc060e6daf060b87d38fd2a38d24bab8210 Mon Sep 17 00:00:00 2001 From: joehan Date: Thu, 11 May 2023 13:06:17 -0700 Subject: [PATCH] Correctly handle optional fields in EventArc emulator (#5819) * Optional attributes shoud actually be optional * add changelog * Fix tests * Actually fix tests --- CHANGELOG.md | 1 + src/emulator/eventarcEmulatorUtils.ts | 4 +-- .../emulators/eventarcEmulatorUtils.spec.ts | 36 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e69de29bb2d..07cf7f67137 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -0,0 +1 @@ +- Fixes an issue in the EventArc emualtor where events missing optional fields would cause crashes. (#5803) diff --git a/src/emulator/eventarcEmulatorUtils.ts b/src/emulator/eventarcEmulatorUtils.ts index 3cc06f5a539..4b3b631c62b 100644 --- a/src/emulator/eventarcEmulatorUtils.ts +++ b/src/emulator/eventarcEmulatorUtils.ts @@ -36,11 +36,11 @@ export function cloudEventFromProtoToJson(ce: any): CloudEvent { } function getOptionalAttribute(ce: any, attr: string, type: string): string | undefined { - return ce["attributes"][attr][type]; + return ce?.["attributes"]?.[attr]?.[type]; } function getRequiredAttribute(ce: any, attr: string, type: string): string { - const val = ce["attributes"][attr][type]; + const val = ce?.["attributes"]?.[attr]?.[type]; if (val === undefined) { throw new FirebaseError("CloudEvent must contain " + attr + " attribute"); } diff --git a/src/test/emulators/eventarcEmulatorUtils.spec.ts b/src/test/emulators/eventarcEmulatorUtils.spec.ts index d7015a11829..d58557f5cb4 100644 --- a/src/test/emulators/eventarcEmulatorUtils.spec.ts +++ b/src/test/emulators/eventarcEmulatorUtils.spec.ts @@ -122,5 +122,41 @@ describe("eventarcEmulatorUtils", () => { expect(got.datacontenttype).to.deep.eq("text/plain"); expect(got.data).to.eq("hello world"); }); + + it("allows optional attribute to not be set", () => { + expect( + cloudEventFromProtoToJson({ + "@type": "type.googleapis.com/io.cloudevents.v1.CloudEvent", + attributes: { + customattr: { + ceString: "custom value", + }, + datacontenttype: { + ceString: "application/json", + }, + time: { + ceTimestamp: "2022-03-16T20:20:42.212Z", + }, + }, + id: "user-provided-id", + source: "/my/functions", + specVersion: "1.0", + textData: '{"hello":"world"}', + type: "some.custom.event", + }) + ).to.deep.eq({ + type: "some.custom.event", + specversion: "1.0", + datacontenttype: "application/json", + id: "user-provided-id", + subject: undefined, + data: { + hello: "world", + }, + source: "/my/functions", + time: "2022-03-16T20:20:42.212Z", + customattr: "custom value", + }); + }); }); });