UNPKG

jdb-lite

Version:

A lightweight schema-based JSON database library with validation

94 lines 2.75 kB
import { DatabaseManager } from './database'; import { Schema } from './schema'; import { ObjectId } from './objectid'; import { createModel } from './model'; class EventEmitter { constructor() { this.events = {}; } on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); return this; } emit(event, ...args) { if (!this.events[event]) { return false; } this.events[event].forEach(listener => listener(...args)); return true; } off(event, listener) { if (!this.events[event]) { return this; } this.events[event] = this.events[event].filter(l => l !== listener); return this; } } class JsonSchemaDBConnection extends EventEmitter { constructor(dbPath) { super(); this.readyState = 0; // 0: disconnected, 1: connected this.models = {}; this.collections = {}; this.name = 'jdb-lite'; this.host = 'localhost'; this.port = 0; this.db = new DatabaseManager(dbPath); this.readyState = 1; } async close() { this.readyState = 0; this.emit('close'); } getDatabase() { return this.db; } } class JsonSchemaDBStatic { constructor() { this.Schema = Schema; this.Types = { ObjectId }; this._models = {}; this.connection = new JsonSchemaDBConnection('.db_json'); } async connect(uri = '.db_json', options) { if (this.connection) { await this.connection.close(); } this.connection = new JsonSchemaDBConnection(uri); // Emit connection events setTimeout(() => { this.connection.emit('connected'); this.connection.emit('open'); }, 0); return this.connection; } async disconnect() { if (this.connection) { await this.connection.close(); } } model(name, schema) { if (!schema && this._models[name]) { return this._models[name]; } if (!schema) { throw new Error(`Schema hasn't been registered for model "${name}".`); } const model = createModel(name, schema, this.connection.getDatabase()); this._models[name] = model; this.connection.models[name] = model; return model; } } // Create the default instance const jsonDB = new JsonSchemaDBStatic(); // Export both the instance and the class for flexibility export default jsonDB; export { JsonSchemaDBStatic as JsonSchemaDB, Schema, ObjectId }; export * from './types'; //# sourceMappingURL=index.js.map