UNPKG

counterfact

Version:

a library for building a fake REST API for testing

51 lines (50 loc) 1.55 kB
import cloneDeep from "lodash/cloneDeep.js"; export class Context { constructor() { } } export function parentPath(path) { return String(path.split("/").slice(0, -1).join("/")) || "/"; } export class ContextRegistry { entries = new Map(); cache = new Map(); seen = new Set(); constructor() { this.add("/", {}); } getContextIgnoreCase(map, key) { const lowerCaseKey = key.toLowerCase(); for (const currentKey of map.keys()) { if (currentKey.toLowerCase() === lowerCaseKey) { return map.get(currentKey); } } return undefined; } add(path, context) { this.entries.set(path, context); this.cache.set(path, cloneDeep(context)); } find(path) { return (this.getContextIgnoreCase(this.entries, path) ?? this.find(parentPath(path))); } update(path, updatedContext) { if (updatedContext === undefined) { return; } if (!this.seen.has(path)) { this.seen.add(path); this.add(path, updatedContext); return; } const context = this.find(path); for (const property in updatedContext) { if (updatedContext[property] !== this.cache.get(path)?.[property]) { context[property] = updatedContext[property]; } } Object.setPrototypeOf(context, Object.getPrototypeOf(updatedContext)); this.cache.set(path, cloneDeep(updatedContext)); } }