UNPKG

@directctrl/fixturelibrary

Version:

Utility library making it easy to work with the open-fixture-library.

101 lines 3.14 kB
"use strict"; /* eslint-disable max-classes-per-file */ Object.defineProperty(exports, "__esModule", { value: true }); exports.FixtureIndex = exports.ItemExistanceError = void 0; /** * When an item call is invalid due to it existing/not existing. */ class ItemExistanceError extends Error { constructor(message) { super(message); this.name = 'ItemExistanceError'; } } exports.ItemExistanceError = ItemExistanceError; /** * The in memory fixture index consisting of {@link IndexItem}s. * * The {@link FileFixtureIndex} is the recommended tool for managing the fixture index, * since it has a smaller memory footprint (in most cases). * This class should **ONLY** be used as the main index, * if local storage isn't viable or if only a few fixtures need to be used. */ class FixtureIndex { constructor() { /** * Internal index object. */ this.index = {}; this.fixtureCache = {}; } /** * @ignore * @returns the index Object. */ getIndex() { return this.index; } /** * @ignore * @param data the object the index should be overwritten with */ setIndex(data) { this.index = data; } /** * Adding a {@link IndexItem} to the index. * @param key fixture key * @param data a {@link IndexItem} object * @param override if a existing entry should be overwritten */ setIndexItem(key, data, override = true) { if (!override && this.hasIndexItem(key)) { throw new ItemExistanceError('This Item already Exists in this FixtureIndex!'); } let item = data; // If its an Alias, the referenced key has to be checked aswell if (data.aliasOf) { if (!this.hasIndexItem(data.aliasOf)) { throw new ItemExistanceError('The referenced item doesn`t exist in the index!'); } // Safety measure to prevent additional data being passed item = { aliasOf: data.aliasOf }; } this.index[key] = item; } /** * Checking if an {@link IndexItem} exists in the index. * @param key fixture key * @returns if the key was found in the index */ hasIndexItem(key) { let flag = false; Object.keys(this.index).forEach((e) => { if (e === key) flag = true; }); return flag; } /** * Fetching an index item. * @param key fixture key * @returns The found IndexItem or undefined if nothing was found. */ getIndexItem(key) { const item = this.index[key]; if (item === undefined) return undefined; // If the IndexItem is an alias, we need to look for the corresponding key recursively if (item.aliasOf) return this.getIndexItem(item.aliasOf); return item; } cacheFixture(key, fixture) { this.fixtureCache[key] = fixture; } fixtureFromCache(key) { return this.fixtureCache[key]; } } exports.FixtureIndex = FixtureIndex; //# sourceMappingURL=fixtureindex.js.map