🪄🪖 Magic-like utilities to simplify development.
npm install trykit
For more in depth documentation about the features, check out the full docs.
-
safetry
: Executes a function safely, avoiding try-catch blocks. -
tryparse
: Parses data against a schema, returning errors safely. -
retry
: Retries a function multiple times with optional delay. -
tryto
: Evaluates an input with fallback for errors. -
TryWhen
: Static methods for conditional value handling. -
merge
: Combines objects or arrays. -
snag
: Chainable error handling for Promises. -
pipeline
: Chain and execute multiple functions.
Safely execute a function or Promise.
Usage:
import { safetry } from "trykit";
const result = await safetry(fetch("/hello"));
if (!result.success) console.error(result.error.message);
console.log(result.data);
Parses input data against a schema safely.
Usage:
import { tryparse } from "trykit";
const schema = z.object({ name: z.string() });
const result = tryparse(schema, { name: "John" });
Retries a function multiple times with configurable delay.
Usage:
import { retry } from "trykit";
const result = await retry(fetch("/data"), { attempts: 3, delay: 100 });
if (!result.success) console.error(result.error.message);
console.log(result.data);
Chain multiple synchronous or asynchronous functions.
-
Methods:
-
.pipe
: Add functions to the chain. -
.execute
: Run the chain.
-
Example:
import { pipeline } from "trykit";
const result = pipeline((n) => n + 1)
.pipe((n) => n * 2)
.execute(5);
console.log(result); // 12
Attempts execution and provides fallback on error.
Usage:
import { tryto } from "trykit";
const result = tryto(() => JSON.parse('{"valid": "json"}'), "fallback");
console.log(result);
Static methods for conditional handling.
Usage:
import { TryWhen } from "trykit";
const result = TryWhen.empty("", "fallback"); // 'fallback'
Combines objects or arrays.
Usage:
import { merge } from "trykit";
const combined = merge({ a: 1 }, { b: 2 }); // { a: 1, b: 2 }
Chainable error handling for Promises.
Usage:
import { snag } from "trykit";
const result = await snag(fetchData)
.on(NetworkError, () => "Using cached data")
.execute();