From fa239e714705d2f4c2977bee4f5e13497181fa43 Mon Sep 17 00:00:00 2001 From: Lebedev Konstantin Date: Tue, 2 Mar 2021 14:07:04 +0300 Subject: [PATCH] feat: + dts (draft) --- dts/fetch.ts | 22 +++++++++++++ dts/typings.ts | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 dts/fetch.ts create mode 100644 dts/typings.ts diff --git a/dts/fetch.ts b/dts/fetch.ts new file mode 100644 index 0000000..6a7574c --- /dev/null +++ b/dts/fetch.ts @@ -0,0 +1,22 @@ +import { + EndpointMap, + TypedFetch, + TypeFetchReqyestInit, + TypedFetchResponse, +} from './typings'; + +export function createTypedFetch(originalFetch: typeof fetch): TypedFetch { + return (url: U, init: TypeFetchReqyestInit) => { + const query = new URLSearchParams(Object(init.body)); + const fetchInit = {...Object(init)} as RequestInit; + let fetchUrl = url as string; + + if (init.method === 'GET') { + fetchUrl += `?${query}`; + } else { + fetchInit.body = query; + } + + return originalFetch(fetchUrl, fetchInit) as TypedFetchResponse; + }; +} diff --git a/dts/typings.ts b/dts/typings.ts new file mode 100644 index 0000000..91a2c6b --- /dev/null +++ b/dts/typings.ts @@ -0,0 +1,86 @@ +export type EndpointAccess = { + headers?: object; + params: object; +}; + +export type Endpoint = { + access: EndpointAccess; + + request: { + method: 'GET' | 'POST'; + + headers?: { + [key: string]: string | undefined; + }; + + params: { + [key: string]: string | number | boolean | undefined + }; + }; + + response: { + headers?: { + [key: string]: string | undefined; + }; + + body: { + status: number; + body: any; + }; + }; +}; + +export type EndpointMap = { + [url: string]: Endpoint; +}; + +export type TypedFetch = < + U extends keyof T, +>( + url: U, + init: TypeFetchReqyestInit, +) => TypedFetchResponse; + +export type TypeFetchReqyestInit< + R extends Endpoint['request'], +> = ( + & Pick + & { + method: R['method']; + body: R['params']; + } +); + +export type TypedFetchResponse = Promise<( + & Pick + & { + url: U; + json(): Promise; + } +)>;