35 lines
998 B
TypeScript
35 lines
998 B
TypeScript
import { type Result } from "@shared/utils/result.ts";
|
|
import { type InferSchema, Schema } from "@shared/utils/validator.ts";
|
|
|
|
export type ExtractRouteParams<T extends string> = T extends string
|
|
? T extends `${infer _Start}:${infer Param}/${infer Rest}`
|
|
? Param | ExtractRouteParams<Rest>
|
|
: T extends `${infer _Start}:${infer Param}` ? Param
|
|
: never
|
|
: never;
|
|
|
|
class ClientApi<
|
|
Path extends string,
|
|
ReqSchema extends Schema<any>,
|
|
ResSchema extends Schema<any>,
|
|
> {
|
|
constructor(
|
|
public readonly path: Path,
|
|
public readonly reqSchema: ReqSchema,
|
|
public readonly resSchema: ResSchema,
|
|
) {
|
|
}
|
|
|
|
makeRequest(
|
|
reqBody: InferSchemaType<ReqSchema>,
|
|
params?: ExtractRouteParams<Path>,
|
|
) {
|
|
const pathWithParams = this.path.split("/").map((segment) => {
|
|
if (segment.startsWith(":")) {
|
|
return params[segment.slice(1)];
|
|
}
|
|
return segment;
|
|
});
|
|
}
|
|
}
|