Basically library structure

This commit is contained in:
mrjvs
2023-08-23 20:07:39 +02:00
parent fe721bee37
commit ef766936dd
12 changed files with 191 additions and 29 deletions

15
src/fetchers/common.ts Normal file
View File

@@ -0,0 +1,15 @@
import { FetcherOptions } from '@/fetchers/types';
// make url with query params and base url used correctly
export function makeFullUrl(url: string, ops?: FetcherOptions): string {
// glue baseUrl and rest of url together
const fullUrl = ops?.baseUrl ?? '';
// TODO make full url
const parsedUrl = new URL(fullUrl);
Object.entries(ops?.query ?? {}).forEach(([k, v]) => {
parsedUrl.searchParams.set(k, v);
});
return parsedUrl.toString();
}

View File

@@ -0,0 +1,15 @@
import { makeFullUrl } from '@/fetchers/common';
import { Fetcher } from '@/fetchers/types';
export function makeStandardFetcher(f: typeof fetch): Fetcher {
const normalFetch: Fetcher = (url, ops) => {
const fullUrl = makeFullUrl(url, ops);
return f(fullUrl, {
method: ops.method,
body: JSON.stringify(ops.body), // TODO content type headers + proper serialization
});
};
return normalFetch;
}

24
src/fetchers/types.ts Normal file
View File

@@ -0,0 +1,24 @@
export type FetcherOptions = {
baseUrl?: string;
headers?: Record<string, string>;
query?: Record<string, string>;
method?: 'GET' | 'POST';
body?: Record<string, any> | string | FormData;
};
export type DefaultedFetcherOptions = {
baseUrl?: string;
body?: Record<string, any> | string | FormData;
headers: Record<string, string>;
query: Record<string, string>;
method: 'GET' | 'POST';
};
export type Fetcher<T = any> = {
(url: string, ops: DefaultedFetcherOptions): T;
};
// this feature has some quality of life features
export type UseableFetcher<T = any> = {
(url: string, ops?: FetcherOptions): T;
};