2024-10-23 02:54:53 -07:00
|
|
|
import { ensureError } from './errors';
|
|
|
|
|
2024-10-10 11:01:38 -07:00
|
|
|
export type ResultOk<T> = { ok: true; result: T };
|
|
|
|
export type ResultError<E> = { ok: false; error: E };
|
|
|
|
export type Result<T, E> = ResultOk<T> | ResultError<E>;
|
|
|
|
|
|
|
|
export const createResultOk = <T>(data: T): ResultOk<T> => ({
|
|
|
|
ok: true,
|
|
|
|
result: data,
|
|
|
|
});
|
|
|
|
|
|
|
|
export const createResultError = <E = unknown>(error: E): ResultError<E> => ({
|
|
|
|
ok: false,
|
|
|
|
error,
|
|
|
|
});
|
2024-10-23 02:54:53 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Executes the given function and converts it to a Result object.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* const result = toResult(() => fs.writeFileSync('file.txt', 'Hello, World!'));
|
|
|
|
*/
|
|
|
|
export const toResult = <T, E extends Error = Error>(fn: () => T): Result<T, E> => {
|
|
|
|
try {
|
|
|
|
return createResultOk<T>(fn());
|
|
|
|
} catch (e) {
|
|
|
|
const error = ensureError(e);
|
|
|
|
return createResultError<E>(error as E);
|
|
|
|
}
|
|
|
|
};
|