From de95fe4a1f10e8d6331c643fa9a471470d42a9b8 Mon Sep 17 00:00:00 2001 From: Tymoteusz Czech <2625371+Tymek@users.noreply.github.com> Date: Wed, 26 Jun 2024 10:06:04 +0200 Subject: [PATCH] fix: ready state when bootstrapping (#218) * fix: ready state when bootstrapping * refactor: fetched from server internal state --- src/index.test.ts | 25 +++++++++++++++++++++++++ src/index.ts | 10 +++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 7eb1ef4..e1d41fc 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1756,3 +1756,28 @@ describe('READY event emission', () => { expect(client.emit).toHaveBeenCalledWith(EVENTS.READY); }); }); + +test('should be in ready state if bootstrapping', (done) => { + const config: IConfig = { + url: 'http://localhost/test', + clientKey: '12', + appName: 'web', + bootstrap: [ + { + enabled: false, + name: 'test-frontend', + variant: { name: 'some-variant', enabled: false }, + impressionData: false, + }, + ], + fetch: async () => {}, + }; + + const client = new UnleashClient(config); + + client.on(EVENTS.READY, () => { + expect(client.isReady()).toBe(true); + client.stop(); + done(); + }); +}); diff --git a/src/index.ts b/src/index.ts index b103250..d888426 100644 --- a/src/index.ts +++ b/src/index.ts @@ -147,6 +147,7 @@ export class UnleashClient extends TinyEmitter { private eventsHandler: EventsHandler; private customHeaders: Record; private readyEventEmitted = false; + private fetchedFromServer = false; private usePOSTrequests = false; private started = false; private sdkState: SdkState; @@ -291,7 +292,7 @@ export class UnleashClient extends TinyEmitter { } private async updateToggles() { - if (this.timerRef || this.readyEventEmitted) { + if (this.timerRef || this.fetchedFromServer) { await this.fetchToggles(); } else if (this.started) { await new Promise((resolve) => { @@ -361,6 +362,8 @@ export class UnleashClient extends TinyEmitter { ) { await this.storage.save(storeKey, this.bootstrap); this.toggles = this.bootstrap; + this.sdkState = 'healthy'; + this.readyEventEmitted = true; this.emit(EVENTS.READY); } @@ -482,9 +485,10 @@ export class UnleashClient extends TinyEmitter { this.sdkState = 'healthy'; } - if (!this.readyEventEmitted) { - this.emit(EVENTS.READY); + if (!this.fetchedFromServer) { + this.fetchedFromServer = true; this.readyEventEmitted = true; + this.emit(EVENTS.READY); } } else if (!response.ok && response.status !== 304) { console.error(