New fetchWithValidation / introducing simpleFetch

This commit is contained in:
Aleksandr Kraiz
2022-05-10 11:44:09 +04:00
parent edc91ecefe
commit 883bcf928f
16 changed files with 350 additions and 117 deletions

28
src/simpleFetch.ts Normal file
View File

@@ -0,0 +1,28 @@
import { Schema, z } from 'zod';
import { RequestInit } from 'node-fetch';
import fetchWithValidation from './fetchWithValidation';
// https://stackoverflow.com/a/64919133
class Wrapper<DataOut, DataIn, ErrorOut, ErrorIn> {
// eslint-disable-next-line class-methods-use-this
wrapped(
url: string,
schema: Schema<DataOut, z.ZodTypeDef, DataIn>,
options?: RequestInit,
errorSchema?: Schema<ErrorOut, z.ZodTypeDef, ErrorIn>,
) {
return fetchWithValidation<DataOut, DataIn, ErrorOut, ErrorIn>(url, schema, options, errorSchema);
}
}
type FetchWithValidationInternalType<O, I, EO, EI> = ReturnType<Wrapper<O, I, EO, EI>['wrapped']>
export default function simpleFetch<O, I, EO, EI, P extends unknown[]>(
f: (...params: P) => FetchWithValidationInternalType<O, I, EO, EI>,
) {
return async (...params: Parameters<typeof f>) => {
const result = await f(...params);
if (result.isErr()) throw new Error(result.error.message);
return result.value;
};
}