UNPKG

ice-db

Version:
155 lines (144 loc) 3.23 kB
const { Collection } = require('./collection'), fs = require('fs') class Ice { /** *Creates an instance of Ice. * @memberof Ice */ constructor() { // initialize an empty list of collections this._collections = {} // initialize default storage params this.storage = { set: false, path: '' } } /** * Sets a storage in a given folder * @param {*} { * path * } * @memberof Ice */ setStorage({ path }) { this.storage = { set: true, path } } /** *Saves all collections in files * * @param {boolean} [sync=false] defines if this operation should be sync or unsync (by default) * @memberof Ice */ save(sync = false) { if (sync) { this._saveSync() } else { this._save() } } /** *Saves all collection sycronously * * @memberof Ice */ _saveSync() { // if folder is not created try { fs.readdirSync(`${this.storage.path}`) } catch (error) { // create it fs.mkdirSync(`${this.storage.path}`) } for (let collection in this._collections) { fs.writeFileSync(`${this.storage.path}/${collection}.json`, JSON.stringify(this._collections[collection].data)) } } /** * Saves all collection asyncronously * @returns {Promise<undefined>} * * @memberof Ice */ async _save() { // if folder is not created try { await fs.readdir(`${this.storage.path}`) } catch (error) { // create it fs.mkdirSync(`${this.storage.path}`) } for (let collection of this._collections) { await fs.writeFile(`${this.storage.path}/${collection}.json`, JSON.stringify(this._collections[collection].data)) } } /** *Create a new collection * * @param {*} { * name * } * @returns {Collection} created collection * @throws error if a collection cannot be created * @memberof Ice */ createCollection({ name }) { if (this._checkCollectionNameVacant(name)) { this[name] = new Collection({ name }) this._collections[name] = this[name] return this[name] } else { throw `Collection "${name}" already exists or it is a reserved identificator` } } /** *Retreives a list of collections in this db * * @returns {[Collection]} all collections * @memberof Ice */ listCollections() { let collections = {} for (let collection in this._collections) { collection = this._collections[collection] collections[collection.name] = collection } return collections } /** *Deletes a collection * * @param {*} collection collection to drop * @memberof Ice */ dropCollection(collection) { let name = (typeof collection) === 'string' ? collection : collection.name this._collections[name].drop(); delete this._collections[name]; delete this[name] } /** *Checks if the given collection name does not already exist * * @param {*} name a name of the collection to check * @returns {Boolean} vacant * @memberof Ice */ _checkCollectionNameVacant(name) { return this[name] ? false : true } } module.exports = { Ice }