import { Low, JSONFile } from 'lowdb' import { type } from 'os' export default function GetDB(util, log, filename = 'db.json') { let fullpath = util.getPathFromRoot('./' + filename) const adapter = new JSONFile(fullpath) const db = new Low(adapter) db.id = 'id' db.createId = function(collection) { if (collection.length) { return (collection[collection.length - 1].id || 0) + 1 } return 1 } db.get = function(collection, id, returnIndex = false) { let col = db.getCollection(collection) for (let i = col.length - 1; i >= 0; i--) { if (col[i][db.id] === id) { if (returnIndex) return i return col[i] } } return null } db.getCollection = function(collection) { if (typeof(collection) === 'string') { return db.data[collection] } return collection } db.upsert = function(collection, item) { let col = db.getCollection(collection) if (item[db.id]) { let i = db.get(col, item[db.id], true) if (i !== null) { col[i] = item return } } item[db.id] = db.createId(col) col.push(item) } db.remove = function(collection, itemOrId) { let col = db.getCollection(collection) let id = itemOrId if (typeof(id) === 'object') { id = id[db.id] } for (let i = col.length - 1; i >= 0; i--) { if (col[i][db.id] === id) { col.splice(i, 1) return true } } return false } return db.read() .then(function() { db.data ||= { core: { app: { active: null, latestInstalled: null, latestVersion: null, versions: [], }, manager: { active: null, latestInstalled: null, latestVersion: null, versions: [], }, version: 1, } } return db.write() }) .then( function() { return db }, function(err) { let wrapped = new Error(`Error writing to ${fullpath}: ${err.code}`) wrapped.code = err.code throw wrapped } ) /* const adapter = new FileAsync(util.getPathFromRoot('./' + filename)) return lowdb(adapter) .then(function(db) { db._.mixin(lodashId) db.adapterFilePath = util.getPathFromRoot('./' + filename) return db.defaults({ core: { "appActive": null, // Current active running "appLatestInstalled": null, // Latest installed version "appLatestVersion": null, // Newest version available "manageActive": null, "manageLatestInstalled": null, "manageLatestVersion": null }, core_appHistory: [], core_manageHistory: [], core_version: 1, }) .write() .then( function() { return db }, function() { throw new Error('Error writing defaults to lowdb'); } ) }) */ }