diff --git a/src/index.test.ts b/src/index.test.ts index 43fe5955..06242cd3 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ /* eslint @typescript-eslint/no-explicit-any: 0 */ -import { DEFAULT_ID, Loader, LoaderOptions } from "."; +import { DEFAULT_ID, Loader, LoaderOptions, LoaderStatus } from "."; jest.useFakeTimers(); @@ -54,6 +54,7 @@ test.each([ ])("createUrl is correct", (options: LoaderOptions, expected: string) => { const loader = new Loader(options); expect(loader.createUrl()).toEqual(expected); + expect(loader.status).toBe(LoaderStatus.INITIALIZED); }); test("uses default id if empty string", () => { @@ -128,6 +129,7 @@ test("script onerror should reject promise", async () => { expect(loader["done"]).toBeTruthy(); expect(loader["loading"]).toBeFalsy(); expect(loader["errors"].length).toBe(1); + expect(loader.status).toBe(LoaderStatus.FAILURE); }); test("script onerror should reject promise with multiple loaders", async () => { @@ -301,6 +303,7 @@ test("singleton should be used", () => { loader["done"] = true; expect(extraLoader["done"]).toBe(loader["done"]); + expect(loader.status).toBe(LoaderStatus.SUCCESS); }); test("singleton should throw with different options", () => { @@ -333,7 +336,7 @@ test("loader should resolve immediately when failed loading", async () => { test("loader should wait if already loading", () => { const loader = new Loader({ apiKey: "foo", retries: 0 }); loader["loading"] = true; - + expect(loader.status).toBe(LoaderStatus.LOADING); loader.load(); }); diff --git a/src/index.ts b/src/index.ts index e8fc2f3a..3218518b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -165,6 +165,16 @@ export interface LoaderOptions { retries?: number; } +/** + * The status of the [[Loader]]. + */ +export enum LoaderStatus { + INITIALIZED, + LOADING, + SUCCESS, + FAILURE, +} + /** * [[Loader]] makes it easier to add Google Maps JavaScript API to your application * dynamically using @@ -314,6 +324,19 @@ export class Loader { }; } + public get status(): LoaderStatus { + if (this.errors.length) { + return LoaderStatus.FAILURE; + } + if (this.done) { + return LoaderStatus.SUCCESS; + } + if (this.loading) { + return LoaderStatus.LOADING; + } + return LoaderStatus.INITIALIZED; + } + private get failed(): boolean { return this.done && !this.loading && this.errors.length >= this.retries + 1; }