UNPKG

node-jet

Version:

Jet Realtime Message Bus for the Web. Daemon and Peer implementation.

87 lines (86 loc) 2.47 kB
import { InvalidArgument } from '../errors.js'; import { pathRules } from '../types.js'; const contains = (what) => (path) => path.includes(what); const containsAllOf = (whatArray) => (path) => { let i; for (i = 0; i < whatArray.length; i = i + 1) { if (!path.includes(whatArray[i])) { return false; } } return true; }; const containsOneOf = (whatArray) => (path) => { let i; for (i = 0; i < whatArray.length; i = i + 1) { if (path.includes(whatArray[i])) { return true; } } return false; }; const startsWith = (what) => (path) => path.startsWith(what); const endsWith = (what) => (path) => path.endsWith(what); const equals = (what) => (path) => path === what; const equalsOneOf = (whatArray) => (path) => { let i; for (i = 0; i < whatArray.length; i = i + 1) { if (path === whatArray[i]) { return true; } } return false; }; const negate = (gen) => ((args) => () => !gen(args)); const generators = { equals, equalsNot: negate(equals), contains, containsNot: negate(contains), containsAllOf, containsOneOf, startsWith, startsNotWith: negate(startsWith), endsWith, endsNotWith: negate(endsWith), equalsOneOf, equalsNotOneOf: negate(equalsOneOf) }; export const createPathMatcher = (options) => { if (!options.path) { return () => true; } const po = options.path; Object.keys(po).forEach((key) => { if (!(key in generators) && key !== 'caseInsensitive') { throw new InvalidArgument('unknown rule ' + key); } }); const predicates = []; pathRules.forEach((name) => { let option = po[name]; if (option) { const gen = generators[name]; if (po.caseInsensitive) { if (Array.isArray(option)) { option = option.map((op) => op.toLowerCase()); } else { option = option.toLowerCase(); } } predicates.push(gen(option)); } }); const applyPredicates = (path) => { for (let i = 0; i < predicates.length; ++i) { if (!predicates[i](path)) { return false; } } return true; }; return predicates.length === 1 ? (path) => predicates[0](path) : (path) => applyPredicates(path); };