@typed/io
Version:
Runtime IO type system
45 lines • 1.6 kB
JavaScript
import { catchFailure, fail } from '@typed/effects';
import { Either, Left, mapLeft } from '@typed/either';
import { curry } from '@typed/lambda';
import { isNotUndefined } from '@typed/logic';
import { Just, Nothing } from '@typed/maybe';
import { toString } from '@typed/strings';
export const DecodeFailure = Symbol.for('DecodeFailure');
export var DecodeError;
(function (DecodeError) {
DecodeError.create = (expected, actual, options = {}) => {
var _a;
return ({
expected,
actual,
key: isNotUndefined(options.key) ? Just.of(options.key) : Nothing,
errors: (_a = options.errors) !== null && _a !== void 0 ? _a : [],
});
};
})(DecodeError || (DecodeError = {}));
export const decode = curry(__decode);
function* __decode(decoder, input) {
return yield* decoder.decode(input);
}
export var Decoder;
(function (Decoder) {
Decoder.fromGuard = (guard, expected) => ({
expected,
*decode(i) {
if (guard.is(i)) {
return i;
}
return yield* fail(DecodeFailure, DecodeError.create(expected, toString(i)));
},
});
})(Decoder || (Decoder = {}));
export const decodeFailure = (e) => fail(DecodeFailure, e);
export function* catchDecodeFailure(effect, onError) {
function* myEffect() {
const x = yield* effect;
return Either.of(x);
}
const either = yield* catchFailure(myEffect(), DecodeFailure, Left.of);
return mapLeft((e) => (onError ? [e, onError(e)] : e), either);
}
//# sourceMappingURL=Decoder.js.map