context
Version:
65 lines (61 loc) • 1.94 kB
JavaScript
;
var vestUtils = require('vest-utils');
const USEX_DEFAULT_ERROR_MESSAGE = 'Not inside of a running context.';
const EMPTY_CONTEXT = Symbol();
/**
* Base context interface.
*/
function createContext(defaultContextValue) {
let contextValue = EMPTY_CONTEXT;
return {
run,
use,
useX,
};
function use() {
return (isInsideContext() ? contextValue : defaultContextValue);
}
function useX(errorMessage) {
vestUtils.invariant(isInsideContext(), vestUtils.defaultTo(errorMessage, USEX_DEFAULT_ERROR_MESSAGE));
return contextValue;
}
function run(value, cb) {
const parentContext = isInsideContext() ? use() : EMPTY_CONTEXT;
contextValue = value;
const res = cb();
contextValue = parentContext;
return res;
}
function isInsideContext() {
return contextValue !== EMPTY_CONTEXT;
}
}
/**
* Cascading context - another implementation of context, that assumes the context value is an object.
* When nesting context runs, the the values of the current layer merges with the layers above it.
*/
function createCascade(init) {
const ctx = createContext();
return {
bind,
run,
use: ctx.use,
useX: ctx.useX,
};
function run(value, fn) {
var _a;
const parentContext = ctx.use();
const out = vestUtils.assign({}, parentContext ? parentContext : {}, (_a = vestUtils.optionalFunctionValue(init, value, parentContext)) !== null && _a !== void 0 ? _a : value);
return ctx.run(Object.freeze(out), fn);
}
function bind(value, fn) {
return function (...runTimeArgs) {
return run(value, function () {
return fn(...runTimeArgs);
});
};
}
}
exports.createCascade = createCascade;
exports.createContext = createContext;
//# sourceMappingURL=context.development.js.map