service-core/core/db.mjs
Jonatan Nilsson 726ac81eb3
All checks were successful
continuous-integration/appveyor/branch AppVeyor build succeeded
Lots more development, git provider finished implementing. Started on creating application
2022-01-21 02:43:48 +00:00

124 lines
3 KiB
JavaScript

import { Low, JSONFile } from 'lowdb'
import { type } from 'os'
import { defaults, isObject } from './defaults.mjs'
export default function GetDB(config, util, log, filename = 'db.json') {
let fullpath = util.getPathFromRoot('./' + filename)
const adapter = new JSONFile(fullpath)
const db = new Low(adapter)
db.id = 'id'
db.config = config
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
}
db.addApplication = function(name) {
db.data.core[name] ||= {}
defaults(db.data.core[name], {
active: null,
latestInstalled: null,
latestVersion: null,
versions: [],
})
}
return db.read()
.then(function() {
if (!isObject(db.data)) {
log.warn(`File ${fullpath} was empty or not a json object, clearing it.`)
db.data = {}
}
defaults(db.data, { core: { version: 1 } })
return db.write()
})
.then(
function() { return db },
function(err) {
let wrapped = new Error(`Error writing to ${fullpath}: ${err.message} (${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'); }
)
})
*/
}