UNPKG

nodedb-json

Version:

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

121 lines 3.97 kB
import _ from 'lodash'; export function matchesConditions(item, conditions) { for (const [field, value] of Object.entries(conditions)) { if (!matchesFieldCondition(_.get(item, field), value)) { return false; } } return true; } export function matchesFieldCondition(actual, condition) { if (!isOperatorObject(condition)) { return actual === condition; } const operators = condition; for (const [operator, expected] of Object.entries(operators)) { switch (operator) { case '$eq': if (actual !== expected) { return false; } break; case '$ne': if (actual === expected) { return false; } break; case '$gt': if (!(actual > expected)) { return false; } break; case '$gte': if (!(actual >= expected)) { return false; } break; case '$lt': if (!(actual < expected)) { return false; } break; case '$lte': if (!(actual <= expected)) { return false; } break; case '$in': if (!Array.isArray(expected)) { throw new Error('Query operator $in expects an array'); } if (!expected.includes(actual)) { return false; } break; case '$nin': if (!Array.isArray(expected)) { throw new Error('Query operator $nin expects an array'); } if (expected.includes(actual)) { return false; } break; case '$startsWith': if (typeof actual !== 'string' || typeof expected !== 'string' || !actual.startsWith(expected)) { return false; } break; case '$endsWith': if (typeof actual !== 'string' || typeof expected !== 'string' || !actual.endsWith(expected)) { return false; } break; case '$contains': if (typeof actual === 'string') { if (typeof expected !== 'string' || !actual.includes(expected)) { return false; } } else if (Array.isArray(actual)) { if (!actual.includes(expected)) { return false; } } else { return false; } break; case '$regex': { if (typeof actual !== 'string') { return false; } const regex = createRegex(expected); if (!regex.test(actual)) { return false; } break; } default: throw new Error(`Unsupported query operator: ${operator}`); } } return true; } export function isOperatorObject(value) { return !!value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date) && Object.keys(value).some(key => key.startsWith('$')); } function createRegex(expected) { return expected instanceof RegExp ? new RegExp(expected.source, expected.flags) : new RegExp(String(expected)); } export function toPredicate(where) { return typeof where === 'function' ? where : (item) => matchesConditions(item, where); } //# sourceMappingURL=matcher.js.map