UNPKG

nodedb-json

Version:

A lightweight JSON-based database for Node.js with TypeScript support, indexing, and complex query capabilities

76 lines 3.01 kB
import { DuplicateIndexError } from '../errors/duplicate-index-error.js'; import { encodeIndexValue } from './index-codec.js'; export function hasIndexDefinition(definitions, key) { return !!definitions[key] && Object.keys(definitions[key]).length > 0; } export function hasIndexOnField(definitions, key, field) { return !!definitions[key] && !!definitions[key][field]; } export function assertUniqueIndexesForKey(definitions, key, data, valueMode = 'strict') { if (!definitions[key]) { return; } for (const field in definitions[key]) { const indexDefinition = definitions[key][field]; if (indexDefinition.type === 'unique') { assertUniqueIndexForDefinition(key, data, indexDefinition, valueMode); } } } export function assertUniqueIndexForDefinition(key, data, indexDefinition, valueMode = 'strict') { const seen = new Set(); for (const item of data) { if (!item || typeof item !== 'object') { continue; } const fieldValue = item[indexDefinition.field]; if (fieldValue === undefined || fieldValue === null) { continue; } const encodedValue = encodeIndexValue(fieldValue, valueMode); if (seen.has(encodedValue)) { throw new DuplicateIndexError(key, indexDefinition.field, fieldValue); } seen.add(encodedValue); } } export function buildIndex(store, key, data, indexDef, valueMode = 'strict') { const indexKey = `${key}:${indexDef.field}`; store[indexKey] = {}; data.forEach((item, index) => { if (!item || typeof item !== 'object') { return; } const fieldValue = item[indexDef.field]; if (fieldValue === undefined || fieldValue === null) { return; } const encodedValue = encodeIndexValue(fieldValue, valueMode); if (indexDef.type === 'unique') { if (encodedValue in store[indexKey]) { throw new DuplicateIndexError(key, indexDef.field, fieldValue); } store[indexKey][encodedValue] = index; } else { if (!store[indexKey][encodedValue]) { store[indexKey][encodedValue] = []; } store[indexKey][encodedValue].push(index); } }); } export function getItemIndexByField(store, key, field, value, valueMode = 'strict') { const indexes = getItemIndexesByField(store, key, field, value, valueMode); return indexes.length > 0 ? indexes[0] : -1; } export function getItemIndexesByField(store, key, field, value, valueMode = 'strict') { const indexKey = `${key}:${field}`; const encodedValue = encodeIndexValue(value, valueMode); if (!store[indexKey] || store[indexKey][encodedValue] === undefined) { return []; } const indexData = store[indexKey][encodedValue]; return typeof indexData === 'number' ? [indexData] : indexData; } //# sourceMappingURL=index-manager.js.map