UNPKG

@thi.ng/interceptors

Version:

Interceptor based event bus, side effect & immutable state handling

56 lines (55 loc) 1.93 kB
import { getInUnsafe } from "@thi.ng/paths/get-in"; import { defSetterUnsafe } from "@thi.ng/paths/setter"; import { defUpdaterUnsafe } from "@thi.ng/paths/updater"; import { FX_CANCEL, FX_DISPATCH, FX_DISPATCH_NOW, FX_STATE } from "./api.js"; const trace = (_, e) => console.log("event:", e); const forwardSideFx = (fxID) => (_, [__, body]) => ({ [fxID]: body !== void 0 ? body : true }); const dispatch = (event) => () => ({ [FX_DISPATCH]: event }); const dispatchNow = (event) => () => ({ [FX_DISPATCH_NOW]: event }); const snapshot = (id = "history") => (_, __, ___, ctx) => ctx[id].record(); const ensurePred = (pred, err) => (state, e, bus, ctx) => !pred(state, e, bus, ctx) ? { [FX_CANCEL]: true, ...err ? err(state, e, bus, ctx) : null } : void 0; const __eventPathState = (state, path, e) => getInUnsafe(state, path ? path(e) : e[1]); const ensureStateLessThan = (max, path, err) => ensurePred((state, e) => __eventPathState(state, path, e) < max, err); const ensureStateGreaterThan = (min, path, err) => ensurePred((state, e) => __eventPathState(state, path, e) > min, err); const ensureStateRange = (min, max, path, err) => ensurePred((state, e) => { const x = __eventPathState(state, path, e); return x >= min && x <= max; }, err); const ensureParamRange = (min, max, value, err) => ensurePred((_, e) => { const x = value ? value(e) : e[1]; return x >= min && x <= max; }, err); const valueSetter = (path, tx) => { const $ = defSetterUnsafe(path); return (state, [_, val]) => ({ [FX_STATE]: $(state, tx ? tx(val) : val) }); }; const valueUpdater = (path, fn) => { const $ = defUpdaterUnsafe(path, fn); return (state, [_, ...args]) => ({ [FX_STATE]: $(state, ...args) }); }; export { dispatch, dispatchNow, ensureParamRange, ensurePred, ensureStateGreaterThan, ensureStateLessThan, ensureStateRange, forwardSideFx, snapshot, trace, valueSetter, valueUpdater };