import type { BackendMiddleware, JioTranslatePlugin, } from '@jiotranslate/core-beta'; import { GetPath, BackendOptions } from './types'; function trimSlashes(path: string) { if (path.endsWith('/')) { return path.slice(0, -1); } return path; } const defaultGetPath: GetPath = ({ namespace, language, prefix }) => { if (namespace) { return `${trimSlashes(prefix)}/${namespace}/${language}.json`; } else { return `${trimSlashes(prefix)}/${language}.json`; } }; function defaultGetData(r: Response) { return r.json(); } const DEFAULT_OPTIONS = { prefix: '/i18n', getPath: defaultGetPath, getData: defaultGetData, headers: { Accept: 'application/json', }, }; function createBackendFetch( options?: Partial ): BackendMiddleware { const { prefix, getPath, getData, headers, ...fetchOptions }: BackendOptions = { ...DEFAULT_OPTIONS, ...options, headers: { ...DEFAULT_OPTIONS.headers, ...options?.headers, }, }; return { getRecord({ namespace, language, fetch }) { const path = getPath({ namespace, language, prefix, }); return fetch(path, { headers, ...fetchOptions }).then((r) => { if (!r.ok) { throw new Error(`${r.url} ${r.status}`); } return getData(r); }); }, }; } export const BackendFetch = (options?: Partial): JioTranslatePlugin => (jiotranslate, tools) => { tools.addBackend(createBackendFetch(options)); return jiotranslate; };