From b4ab1d518fc5f81611435b13bf4e8adcdda68065 Mon Sep 17 00:00:00 2001 From: Tymoteusz Czech <2625371+Tymek@users.noreply.github.com> Date: Fri, 20 Sep 2024 11:53:37 +0200 Subject: [PATCH 1/2] fix: prevent evaluateFlags from throwing an error if definitions are not provided --- lib/src/evaluateFlags.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/src/evaluateFlags.ts b/lib/src/evaluateFlags.ts index 3298a0e..027f96f 100644 --- a/lib/src/evaluateFlags.ts +++ b/lib/src/evaluateFlags.ts @@ -12,7 +12,17 @@ export const evaluateFlags = ( ): { toggles: IToggle[]; } => { - const engine = new ToggleEngine(definitions); + let engine: ToggleEngine; + try { + engine = new ToggleEngine(definitions); + } catch (error) { + console.error( + "Unleash: Failed to evaluate flags from provided definitions", + error + ); + return { toggles: [] }; + } + const defaultContext: Context = { currentTime: new Date(), appName: From f158414a78f8b98b7ebf945c16d10f9d1055309f Mon Sep 17 00:00:00 2001 From: Tymoteusz Czech <2625371+Tymek@users.noreply.github.com> Date: Fri, 20 Sep 2024 13:43:20 +0200 Subject: [PATCH 2/2] test evaluateFlags error catching --- lib/src/evaluateFlags.test.ts | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 lib/src/evaluateFlags.test.ts diff --git a/lib/src/evaluateFlags.test.ts b/lib/src/evaluateFlags.test.ts new file mode 100644 index 0000000..a3a0278 --- /dev/null +++ b/lib/src/evaluateFlags.test.ts @@ -0,0 +1,43 @@ +import { evaluateFlags } from "./evaluateFlags"; +import type { ClientFeaturesResponse } from "unleash-client"; + +describe("evaluateFlags", () => { + it("should return toggles when engine initializes successfully", () => { + const definitions: ClientFeaturesResponse = { + version: 1, + features: [ + { name: "featureA", enabled: true }, + { name: "featureB", enabled: false }, + ], + }; + + const result = evaluateFlags(definitions, {}); + + expect(result).toEqual({ + toggles: [ + { + name: "featureA", + enabled: true, + impressionData: false, + variant: { + enabled: false, + feature_enabled: true, + name: "disabled", + }, + }, + ], + }); + }); + + it("should return empty toggles when engine initialization fails", () => { + const definitions = { + message: "Invalid definitions", + }; + + const result = evaluateFlags(definitions as any, {}); + + expect(result).toEqual({ + toggles: [], + }); + }); +});