UNPKG

@remcostoeten/fync

Version:

Unified TypeScript library for 9 popular APIs with consistent functional architecture

67 lines (66 loc) 1.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.failure = failure; exports.isFailure = isFailure; exports.isSuccess = isSuccess; exports.mapResult = mapResult; exports.success = success; exports.tryCatch = tryCatch; exports.unwrap = unwrap; exports.unwrapOr = unwrapOr; /** * Result type for predictable error handling * Following the pattern specified in architecture.md */ /** * Helper functions for creating and handling results */ function success(value) { return { ok: true, value }; } function failure(error) { return { ok: false, error }; } function isSuccess(result) { return result.ok === true; } function isFailure(result) { return result.ok === false; } function unwrap(result) { if (isSuccess(result)) { return result.value; } throw new Error(typeof result.error === 'string' ? result.error : 'Operation failed'); } function unwrapOr(result, defaultValue) { return isSuccess(result) ? result.value : defaultValue; } function mapResult(result, fn) { if (isSuccess(result)) { return success(fn(result.value)); } return result; } async function tryCatch(fn, errorTransform) { try { const value = await fn(); return success(value); } catch (error) { if (errorTransform) { return failure(errorTransform(error)); } if (error instanceof Error) { return failure(error.message); } return failure(String(error)); } }