suma-db
Version:
A Brazilian database that supports JSON(JavaScript Object Notation)
88 lines (74 loc) • 3.07 kB
JavaScript
const fs = require("fs"),
{ sep } = require("path"),
event = require("events");
module.exports = class Base extends event {
constructor(path = './sumadb.json', content = {}, prefix = ":", spaces) {
super()
path = path.path ? path.path || path.filePath : path
if (typeof path !== 'string') path = './sumadb.json'
if (typeof content !== 'object') content = {}
content = JSON.stringify(content, null, 4);
if (typeof prefix !== 'string') prefix = ":"
this.path = path
this.prefix = prefix
this.spaces = spaces
const pathAll = process.cwd().replace(/\\/g, "/") + '/'
if (path.startsWith(pathAll)) path = path.replace(pathAll, '')
if (path.startsWith(`.${sep}`)) {
path = path.slice(1);
}
path = path.replace(/\.\w{1,6}$/gi, '')
path = path.replace(/\.{1,2}\/+(\.{1,2}\/)?/gi, "")
this.path = `./${path}.json`
if (!fs.existsSync(this.path)) {
fs.writeFileSync(this.path, content)
}
}
setValue(val = {}, spaces = this.spaces) {
if (isNaN(spaces)) spaces = 4
if (typeof val !== 'object') val = {}
fs.writeFileSync(this.path, JSON.stringify(val, null, spaces), 'utf-8')
}
SumaDBNotation(key, db, value = null, prefix = this.prefix) {
const valueSet = []
function stringParaObjectDividoPeloPrefixo(objeto, keys, v, prefix) {
if (keys.key) keys = keys.key
if (keys.endsWith(prefix)) keys = keys.slice(0, keys.length - 1);
let chaves = keys.split(prefix)
const transfer = function (obj, key) {
if (key.length > 1) {
if (typeof obj[key[0]] !== 'object' || Array.isArray(obj[key[0]]))
obj[key[0]] = {}
transfer(obj[key[0]], key.slice(1))
} else {
valueSet.push({ [key[0]]: v })
obj[key[0]] = v
}
}
transfer(objeto, chaves)
return objeto
}
stringParaObjectDividoPeloPrefixo(db, key, value, prefix)
return { n: valueSet[0], data: db }
}
read(collection = false) {
return JSON.parse(fs.readFileSync(this.path, 'utf-8'))
}
prepare(key, prefix, val, db = {}) {
let dbReference = db, keys = key.split(prefix)
for (false; keys.length > 1; false) {
const _KeyShift = keys.shift()
dbReference = dbReference[_KeyShift] = dbReference[_KeyShift] || {}
}
dbReference[keys] = val
return db
}
preparer(key, db, prefix = this.prefix) {
let dbReference = db, keys = key.split(prefix)
for (false; keys.length > 1; false) {
const _KeyShift = keys.shift()
dbReference = dbReference[_KeyShift] = dbReference[_KeyShift] || {}
}
return dbReference[keys]
}
}