UNPKG

@jokoor/sdk

Version:
105 lines 2.33 kB
"use strict"; /** * Result type for API responses following the {data, error} pattern * Similar to Go's error handling approach */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ok = ok; exports.err = err; exports.isOk = isOk; exports.isErr = isErr; exports.unwrap = unwrap; exports.unwrapOr = unwrapOr; exports.map = map; exports.chain = chain; exports.fromPromise = fromPromise; exports.all = all; /** * Helper function to create a successful result */ function ok(data) { return { data, error: null }; } /** * Helper function to create an error result */ function err(error) { return { data: null, error }; } /** * Type guard to check if a result is successful */ function isOk(result) { return result.error === null; } /** * Type guard to check if a result is an error */ function isErr(result) { return result.error !== null; } /** * Extract data from a result or throw if it's an error * Useful for migrating from throw-based code */ function unwrap(result) { if (isErr(result)) { throw new Error(result.error); } return result.data; } /** * Extract data from a result or return a default value */ function unwrapOr(result, defaultValue) { if (isErr(result)) { return defaultValue; } return result.data; } /** * Map a successful result to a new value */ function map(result, fn) { if (isErr(result)) { return result; } return ok(fn(result.data)); } /** * Chain results together - useful for sequential operations */ function chain(result, fn) { if (isErr(result)) { return result; } return fn(result.data); } /** * Convert a Promise that might throw into a Result */ async function fromPromise(promise) { try { const data = await promise; return ok(data); } catch (error) { const message = error instanceof Error ? error.message : String(error); return err(message); } } /** * Convert multiple Results into a single Result containing an array * If any result is an error, returns that error */ function all(results) { const data = []; for (const result of results) { if (isErr(result)) { return result; } data.push(result.data); } return ok(data); } //# sourceMappingURL=result.js.map