Skip to content

Commit

Permalink
fix: remove whitespace from URL
Browse files Browse the repository at this point in the history
  • Loading branch information
robrechtme committed Oct 18, 2022
1 parent 2cc1986 commit 5e8992c
Showing 1 changed file with 33 additions and 17 deletions.
50 changes: 33 additions & 17 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,24 @@ import {
Translations,
} from "../../types";

const fetchApi = async <T>(path: string, opts = {}) => {
const response = await fetch(`https://localise.biz/api${path}`, opts);
const BASE_URL = "https://localise.biz/api";

const fetchApi = async <T>(
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}`);
}
Expand All @@ -17,11 +33,11 @@ const fetchApi = async <T>(path: string, opts = {}) => {

export const apiPull = async (key: string, options: PullOptions = {}) => {
const translations = await fetchApi<Translations>(
`/export/all.json?${new URLSearchParams({ key, ...options }).toString()}`
);
const locales = await fetchApi<ProjectLocale[]>(
`/locales?${new URLSearchParams({ key }).toString()}`
key,
"/export/all.json",
options
);
const locales = await fetchApi<ProjectLocale[]>(key, "/locales");
if (locales?.length === 1) {
return { [locales[0].code]: translations };
}
Expand All @@ -35,18 +51,18 @@ export const apiPush = (
options: PushOptions = {}
) =>
fetchApi<void>(
`/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),
Expand Down

0 comments on commit 5e8992c

Please sign in to comment.