From 2d6d83ccb287f3e7f42e8e44087e7219b97659eb Mon Sep 17 00:00:00 2001 From: dswbx Date: Sat, 25 Jan 2025 19:29:36 +0100 Subject: [PATCH] add fetcher option to api to allow local calls --- app/__test__/api/ModuleApi.spec.ts | 10 ++-------- app/src/Api.ts | 19 ++++++++++++------- app/src/modules/ModuleApi.ts | 7 ++++--- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/app/__test__/api/ModuleApi.spec.ts b/app/__test__/api/ModuleApi.spec.ts index 5fb6976..9577fd1 100644 --- a/app/__test__/api/ModuleApi.spec.ts +++ b/app/__test__/api/ModuleApi.spec.ts @@ -27,10 +27,7 @@ describe("ModuleApi", () => { it("fetches endpoint", async () => { const app = new Hono().get("/endpoint", (c) => c.json({ foo: "bar" })); - const api = new Api({ host }); - - // @ts-expect-error it's protected - api.fetcher = app.request as typeof fetch; + const api = new Api({ host }, app.request as typeof fetch); const res = await api.get("/endpoint"); expect(res.res.ok).toEqual(true); @@ -41,10 +38,7 @@ describe("ModuleApi", () => { it("has accessible request", async () => { const app = new Hono().get("/endpoint", (c) => c.json({ foo: "bar" })); - const api = new Api({ host }); - - // @ts-expect-error it's protected - api.fetcher = app.request as typeof fetch; + const api = new Api({ host }, app.request as typeof fetch); const promise = api.get("/endpoint"); expect(promise.request).toBeDefined(); diff --git a/app/src/Api.ts b/app/src/Api.ts index 835ff14..2310c0f 100644 --- a/app/src/Api.ts +++ b/app/src/Api.ts @@ -23,6 +23,7 @@ export type ApiOptions = { headers?: Headers; key?: string; localStorage?: boolean; + fetcher?: typeof fetch; }; export type AuthState = { @@ -163,14 +164,18 @@ export class Api { headers: this.options.headers, token_transport: this.token_transport }; + const fetcher = this.options.fetcher; - this.system = new SystemApi(baseParams); - this.data = new DataApi(baseParams); - this.auth = new AuthApi({ - ...baseParams, - onTokenUpdate: (token) => this.updateToken(token, true) - }); - this.media = new MediaApi(baseParams); + this.system = new SystemApi(baseParams, fetcher); + this.data = new DataApi(baseParams, fetcher); + this.auth = new AuthApi( + { + ...baseParams, + onTokenUpdate: (token) => this.updateToken(token, true) + }, + fetcher + ); + this.media = new MediaApi(baseParams, fetcher); } } diff --git a/app/src/modules/ModuleApi.ts b/app/src/modules/ModuleApi.ts index 882cb90..a088170 100644 --- a/app/src/modules/ModuleApi.ts +++ b/app/src/modules/ModuleApi.ts @@ -23,9 +23,10 @@ export type ApiResponse = { export type TInput = string | (string | number | PrimaryFieldType)[]; export abstract class ModuleApi { - protected fetcher?: typeof fetch; - - constructor(protected readonly _options: Partial = {}) {} + constructor( + protected readonly _options: Partial = {}, + protected fetcher?: typeof fetch + ) {} protected getDefaultOptions(): Partial { return {};