diff --git a/src/lib/api.ts b/src/lib/api.ts index 2031441..08027d6 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -6,8 +6,24 @@ import { Translations, } from "../../types"; -const fetchApi = async (path: string, opts = {}) => { - const response = await fetch(`https://localise.biz/api${path}`, opts); +const BASE_URL = "https://localise.biz/api"; + +const fetchApi = async ( + apiKey: string, + endpoint: string, + searchParams = {}, + fetchOptions: RequestInit = {} +) => { + const url = new URL(`${BASE_URL}${endpoint}`); + url.search = new URLSearchParams(searchParams).toString(); + + const response = await fetch(url, { + ...fetchOptions, + headers: { + ...(fetchOptions?.headers || {}), + Authorization: `Loco ${apiKey}`, + }, + }); if (!response.ok) { throw new Error(`HTTPError: ${response.status} ${response.statusText}`); } @@ -17,11 +33,11 @@ const fetchApi = async (path: string, opts = {}) => { export const apiPull = async (key: string, options: PullOptions = {}) => { const translations = await fetchApi( - `/export/all.json?${new URLSearchParams({ key, ...options }).toString()}` - ); - const locales = await fetchApi( - `/locales?${new URLSearchParams({ key }).toString()}` + key, + "/export/all.json", + options ); + const locales = await fetchApi(key, "/locales"); if (locales?.length === 1) { return { [locales[0].code]: translations }; } @@ -35,18 +51,18 @@ export const apiPush = ( options: PushOptions = {} ) => fetchApi( - `/import/json? - ${new URLSearchParams({ key, - locale, - ...Object.keys(options).reduce( - (acc, key) => ({ - ...acc, - [key]: options[key as keyof PushOptions]?.toString(), - }), - {} - ), - }).toString()}`, + "/import/json", + { + locale, + ...Object.keys(options).reduce( + (acc, key) => ({ + ...acc, + [key]: options[key as keyof PushOptions]?.toString(), + }), + {} + ), + }, { method: "POST", body: JSON.stringify(translations),