UNPKG

alinea

Version:

[![npm](https://img.shields.io/npm/v/alinea.svg)](https://npmjs.org/package/alinea) [![install size](https://packagephobia.com/badge?p=alinea)](https://packagephobia.com/result?p=alinea)

127 lines (125 loc) 3.02 kB
import "../chunks/chunk-U5RRZUYZ.js"; // src/core/Outcome.ts import { HttpError } from "./HttpError.js"; function outcome(run) { try { if (typeof run === "function") { const result = run(); if (result instanceof Promise) return outcome(result); return Outcome.Success(result); } if (run instanceof Promise) return run.then(Outcome.Success).catch(Outcome.Failure); return Outcome.Success(run); } catch (e) { return Outcome.Failure(e); } } ((outcome2) => { function succeeds(run) { const result = outcome2(run); if (result instanceof Promise) return result.then((outcome3) => outcome3.isSuccess()); return result.isSuccess(); } outcome2.succeeds = succeeds; function fails(run) { const result = outcome2(run); if (result instanceof Promise) return result.then((outcome3) => outcome3.isFailure()); return result.isFailure(); } outcome2.fails = fails; })(outcome || (outcome = {})); var Outcome; ((Outcome2) => { function fromJSON(json) { if (json.success) return Success(json.data); const error = new HttpError(json.error.status, json.error.message); error.stack = json.error.stack; return Failure(error); } Outcome2.fromJSON = fromJSON; function unpack(outcome2) { if (outcome2.isSuccess()) return outcome2.value; throw outcome2.error; } Outcome2.unpack = unpack; function isOutcome(value) { return value instanceof OutcomeImpl; } Outcome2.isOutcome = isOutcome; function Success(data) { return new SuccessOutcome(data); } Outcome2.Success = Success; function Failure(error) { return new FailureOutcome( error instanceof Error ? error : new Error(error) ); } Outcome2.Failure = Failure; class OutcomeImpl { constructor(success) { this.success = success; } isSuccess() { return this.success; } isFailure() { return !this.success; } } Outcome2.OutcomeImpl = OutcomeImpl; class SuccessOutcome extends OutcomeImpl { constructor(value) { super(true); this.value = value; } status = 200; error = void 0; *[Symbol.iterator]() { yield this.value; yield void 0; } map(fn) { return Success(fn(this.value)); } toJSON() { return { success: true, data: this.value }; } } class FailureOutcome extends OutcomeImpl { constructor(error) { super(false); this.error = error; this.status = error instanceof HttpError ? error.code : 500; } status; value = void 0; *[Symbol.iterator]() { yield void 0; yield this.error; } map(fn) { return this; } toJSON() { return { success: false, error: { message: String(this.error), stack: this.error instanceof Error ? this.error.stack : void 0, status: this.status } }; } } })(Outcome || (Outcome = {})); export { Outcome, outcome };