mirror of
https://github.com/orionprotocol/sdk.git
synced 2026-03-16 07:02:36 +03:00
New fetchWithValidation / introducing simpleFetch
This commit is contained in:
28
src/simpleFetch.ts
Normal file
28
src/simpleFetch.ts
Normal 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;
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user