UNPKG

nodedb-json

Version:

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

63 lines 1.8 kB
import { matchesConditions } from '../query/matcher.js'; export class Collection { constructor(db, key) { this.db = db; this.key = key; } all() { const data = this.db.get(this.key); return Array.isArray(data) ? data : []; } insert(item) { this.db.push(this.key, item); return this; } findOne(where) { if (typeof where === 'function') { return this.db.find(this.key, where); } return this.db.find(this.key, item => this._matches(item, where)); } findMany(where) { if (!where) { return this.all(); } if (typeof where === 'function') { return this.db.filter(this.key, where); } return this.db.filter(this.key, item => this._matches(item, where)); } updateOne(where, updater) { const predicate = this._toPredicate(where); this.db.update(this.key, predicate, updater); return this; } deleteOne(where) { const predicate = this._toPredicate(where); let deleted = false; this.db.delete(this.key, item => { if (deleted || !predicate(item)) { return false; } deleted = true; return true; }); return this; } query(options = {}) { return this.db.query(this.key, options); } createIndex(indexDefinition) { this.db.createIndex(this.key, indexDefinition); return this; } _toPredicate(where) { return typeof where === 'function' ? where : (item) => this._matches(item, where); } _matches(item, where) { return matchesConditions(item, where); } } //# sourceMappingURL=collection.js.map