🪄🪖 Simple magic-like utilities to ease your development experience.
npm install trykit
-
safetry
- call your function without wrapping it in a try-catch block, and check if it throws; -
tryparse
- parse data in a schema, without it erroring. -
retry
- retry a function n-times;
safetry<T>(callback: Promise<T> | (() => Promise<T>) | (() => T)): Promise<SafeTryResult<T>> | SafeTryResult<T>
-
callback: Promise<T> | (() => Promise<T> | () => T
- function or promise returntype like with inferedT
;
-
SafeTryResult<T>
- result object withsuccess
property to indicate if there is an error or you can get the data;
import { safetry } from "trykit";
const result = await safetry(fetch("/hello"));
if (!result.success) console.error(result.error.message);
console.log(result.data);
tryparse<T>(schema: TryParseSchema<T>, input: unknown, ...args: unknown[]): SafeTryResult<T>
-
schema: TryParseSchema<T>
- schema with aparse
function in it that returns typeT
; -
input: unknown
- first argument passed to theschema.parse
function, useargs
for rest parameters;
-
SafeTryResult<T>
- see thesafetry
function;
import { tryparse } from "trykit";
const zodSchema = z.object({
hello: z.string(),
});
const zodResult = tryparse(zodSchema, { bye: "good day" });
const jsonResult = tryparse(JSON, jsonString);
retry<T>(callback: Promise<T> | (() => Promise<T>), config?: Partial<RetryConfig>): Promise<SafeTryResult<T>>
-
callback: Promise<T> | (() => Promise<T> | () => T
- function or promise returntype like with inferedT
; -
config?: RetryConfig
- (optional) configuration for the retries of typeRetryConfig
;
RetryConfig
:
-
attempts?: number
- (optional) number of times the callback can be called before returning the error; -
delay?: number
- (optional) delay in milliseconds to wait for the next iteration; -
factor?: number
- (optional) multiply the delay with a factor (default 2);
-
SafeTryResult<T>
- see thesafetry
function;
const result = await retry(fetch("/unknown"), { attempts: 5, delay: 50, factor: 1 });
if (!result.success) console.error(result.error.message);
console.log(result.data);