dbd.db
Version:
A Lightweight Schema-Free Object-Oriented LocalDatabase for Development and Production Purpose
92 lines (68 loc) • 1.97 kB
JavaScript
const fs = require('fs')
const Util = require('../util')
const DBDError = require('./dbdError')
const BaseCollection = require('./collection')
const { EventEmitter } = require('events')
/**
* The main hub to interact with the database
* @extends {EventEmitter}
*/
class Database extends EventEmitter {
/**
* @param {!String} name The name for the storage
*/
constructor(name) {
if (typeof name !== 'string') throw new DBDError('Name must be typeof string!', 1)
super()
this._waitForReady = []
this.ready = false
this.name = name
this.cache = new Map()
this.collections = new Map()
this.sizeCache = Object.create(null)
this.once('ready', () => {
this.ready = true
let i = 0
while (i < this._waitForReady.length) {
const resolve = this._waitForReady.shift()
resolve()
i++
}
})
new Promise(async (resolve, reject) => {
await Util.createStorage(name).catch(reject)
this.emit('ready')
})
}
/**
* The database name
* @returns {String}
*/
get displayName() {
return this.name
}
/**
* The condition if the Database is ready to use
* @returns {Boolean}
*/
get isReady() {
return this.ready
}
/**
* The hub to interact with the collections
* @param {!Object} opts The options for the collection
* @returns {BaseCollection}
*/
collection(opts) {
if (typeof opts.name !== 'string') throw new DBDError('Collection name must be a string!', 2)
if (opts.name.includes('/')) throw new DBDError('/ in filename is not allowed!', 4)
if (opts.name.includes('\\')) throw new DBDError('\ in filename is not allowed!', 4)
if (typeof opts.ttl === 'number' && opts.ttl < 5) throw new DBDError('TTL check interval must be 5 seconds at minimal!', 5)
if (this.collections.has(opts.name))
return this.collections.get(opts.name)
const col = new BaseCollection(this, opts)
this.collections.set(opts.name, col)
return col
}
}
module.exports = Database