tryless
Version:
Type-safe error handling for TypeScript without try-catch hell
95 lines • 3.07 kB
JavaScript
/* eslint-disable @typescript-eslint/no-explicit-any */
import { UnknownError } from './result/constants';
import { Err, Ok } from './result/classes';
import { ok } from './result/functions';
/**
* Creates a curried function that transforms data and wraps it in a success result.
* Useful for promise chains and function composition.
*
* @template T - Type of the input data
* @template R - Type of the transformed data
* @param map - Function to transform the input data
* @returns A function that takes data, transforms it, and returns an Ok result
*
* @example
* ```ts
* import { okFulfilled } from 'tryless';
*
* // Simple transformation
* const double = okFulfilled((n: number) => n * 2);
* const result = double(5);
* // { success: true, data: 10 }
*
* // Use in promise chains
* fetch('https://api.example.com/user')
* .then(res => res.json())
* .then(okFulfilled(user => user.name))
* .then(result => {
* if (result.success) {
* console.log(result.data); // user name
* }
* });
* ```
*/
export function okFulfilled(map) {
return (data) => ok(map(data));
}
/**
* Creates a curried error factory that wraps rejection reasons in error results.
* Particularly useful for converting promise rejections in complex chains.
*
* **Note:** For simple promise wrapping, prefer `resultfy()` which is more concise.
*
* @template E - String literal type for the error identifier
* @param error - The error identifier to use for all rejections
* @returns A function that takes a reason and returns an Err result
*
* @example
* ```ts
* import { errReject, ok, resultfy } from 'tryless';
*
* // Basic usage
* const onReject = errReject('FetchError');
* const result = onReject('Network down');
* // { success: false, error: 'FetchError', reason: 'Network down' }
*
* // Use in complex promise chains
* const userResult = await fetch('https://api.example.com/user')
* .then(ok, errReject('user:fetch-error'))
* .then(res => res.success ? res.data.json() : res)
* .then(ok, errReject('user:parse-error'));
*
* // For simpler cases, prefer resultfy:
* const userResult = await resultfy(
* fetch('https://api.example.com/user'),
* 'user:fetch-error'
* );
* ```
*/
export function errReject(error) {
return function rejectWrapper(reason) {
return new Err(error, reason, rejectWrapper);
};
}
export function resultfy(fn, fnError) {
const error = fnError ?? UnknownError;
if (fn instanceof Promise) {
return fn.then(ok, errReject(error));
}
if (typeof fn !== "function") {
throw new Error("fn must be a function or a promise");
}
return (function wrapper(...args) {
try {
const result = fn(...args);
if (result instanceof Promise) {
return result.then(ok, (reason) => new Err(error, reason, wrapper));
}
return ok(result);
}
catch (reason) {
return new Err(error, reason, wrapper);
}
});
}
//# sourceMappingURL=helpers.js.map