-
Notifications
You must be signed in to change notification settings - Fork 88
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #18 from deco-cx/feat/clients
feat: use the new http client implementation
- Loading branch information
Showing
42 changed files
with
813 additions
and
732 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,151 @@ | ||
import { RequestInit } from "$live/runtime/fetch/mod.ts"; | ||
import { fetchSafe } from "./fetch.ts"; | ||
|
||
const HTTP_VERBS = new Set( | ||
[ | ||
"GET", | ||
"PUT", | ||
"POST", | ||
"DELETE", | ||
"PATCH", | ||
"HEAD", | ||
] as const, | ||
); | ||
|
||
export class HttpError extends Error { | ||
constructor(public status: number, message?: string, options?: ErrorOptions) { | ||
super(message, options); | ||
this.name = `HttpError ${status}`; | ||
} | ||
} | ||
|
||
export interface TypedRequestInit<T> extends Omit<RequestInit, "body"> { | ||
body: T; | ||
} | ||
|
||
export interface TypedResponse<T> extends Response { | ||
json: () => Promise<T>; | ||
} | ||
|
||
type HttpVerb = typeof HTTP_VERBS extends Set<infer Verb> ? Verb : never; | ||
|
||
type URLPatternParam = string | number; | ||
|
||
type URLPatternParams<URL extends string> = URL extends | ||
`/:${infer param}/${infer rest}` | ||
? { [key in param]: URLPatternParam } & URLPatternParams<`/${rest}`> | ||
: URL extends `/:${infer param}?` ? { [key in param]?: URLPatternParam } | ||
: URL extends `/:${infer param}` ? { [key in param]: URLPatternParam } | ||
: URL extends `/*?` ? { "*"?: URLPatternParam | URLPatternParam[] } | ||
: URL extends `/*` ? { "*": URLPatternParam | URLPatternParam[] } | ||
: URL extends `/*${infer param}?` | ||
? { [key in param]: URLPatternParam | URLPatternParam[] } | ||
: URL extends `/*${infer param}` | ||
? { [key in param]: URLPatternParam | URLPatternParam[] } | ||
: URL extends `/${string}/${infer rest}` ? URLPatternParams<`/${rest}`> | ||
: {}; | ||
|
||
type ClientOf<T> = { | ||
[key in (keyof T) & `${HttpVerb} /${string}`]: key extends | ||
`${HttpVerb} /${infer path}` ? T[key] extends { | ||
response?: infer ResBody; | ||
body: infer ReqBody; | ||
searchParams?: infer Params; | ||
} ? ( | ||
params: URLPatternParams<`/${path}`> & Params, | ||
init: TypedRequestInit<ReqBody>, | ||
) => Promise<TypedResponse<ResBody>> | ||
: T[key] extends { | ||
response?: infer ResBody; | ||
searchParams?: infer Params; | ||
} ? ( | ||
params: URLPatternParams<`/${path}`> & Params, | ||
init?: Omit<RequestInit, "body">, | ||
) => Promise<TypedResponse<ResBody>> | ||
: never | ||
: never; | ||
}; | ||
|
||
export interface HttpClientOptions { | ||
base: string; | ||
headers?: Headers; | ||
fetcher?: typeof fetch; | ||
} | ||
|
||
export const createHttpClient = <T>({ | ||
base, | ||
headers: defaultHeaders, | ||
fetcher = fetchSafe, | ||
}: HttpClientOptions): ClientOf<T> => | ||
new Proxy({} as ClientOf<T>, { | ||
get: (_target, prop) => { | ||
if (typeof prop !== "string") { | ||
throw new TypeError(`HttpClient: Uknown path ${typeof prop}`); | ||
} | ||
|
||
const [method, path] = prop.split(" "); | ||
|
||
// @ts-expect-error if not inside, throws | ||
if (!HTTP_VERBS.has(method)) { | ||
throw new TypeError(`HttpClient: Verb ${method} is not allowed`); | ||
} | ||
|
||
return ( | ||
params: Record<string, string | number | string[] | number[]>, | ||
init: RequestInit, | ||
) => { | ||
const mapped = new Map(Object.entries(params)); | ||
|
||
const compiled = path | ||
.split("/") | ||
.flatMap((segment) => { | ||
const isTemplate = segment.at(0) === ":" || segment.at(0) === "*"; | ||
const isRequred = segment.at(-1) !== "?"; | ||
|
||
if (!isTemplate) { | ||
return segment; | ||
} | ||
|
||
const name = segment.slice(1, !isRequred ? -1 : undefined); | ||
const param = mapped.get(name); | ||
mapped.delete(name); | ||
|
||
if (param === undefined && isRequred) { | ||
throw new TypeError(`HttpClient: Missing ${name} at ${path}`); | ||
} | ||
|
||
return param; | ||
}) | ||
.filter((s) => s !== undefined) | ||
.join("/"); | ||
|
||
const url = new URL(compiled, base); | ||
mapped.forEach((value, key) => { | ||
const arrayed = Array.isArray(value) ? value : [value]; | ||
arrayed.forEach((item) => url.searchParams.append(key, `${item}`)); | ||
}); | ||
|
||
const shouldStringifyBody = init.body != null && | ||
typeof init.body !== "string" && | ||
!(init.body instanceof ReadableStream) && | ||
!(init.body instanceof FormData) && | ||
!(init.body instanceof URLSearchParams) && | ||
!(init.body instanceof Blob) && | ||
!(init.body instanceof ArrayBuffer); | ||
|
||
const headers = new Headers(init.headers); | ||
defaultHeaders?.forEach((value, key) => headers.set(key, value)); | ||
|
||
const body = shouldStringifyBody | ||
? JSON.stringify(init.body) | ||
: undefined; | ||
|
||
return fetcher(url, { | ||
...init, | ||
headers, | ||
method, | ||
body, | ||
}); | ||
}; | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.