UNPKG

strong-db

Version:

Uma simples Database em JSON para Node.js. (Brasileira)

193 lines (158 loc) 5.94 kB
const fs = require("fs"); const object = require('object.mn') let validateJSON = function(fileContent) { try { JSON.parse(fileContent); } catch (e) { throw new Error('O Arquivo fornecido está vazio ou não é um JSON válido.'); } return true; }; const defaultOptions = { edit: true }; function StrongDB(filePath, options) { if (!filePath || !filePath.length) { throw new Error('Você se esqueceu deu definir um Caminho JSON. (path, options)'); } else { this.filePath = filePath; } if (options) { for (let key in defaultOptions) { if (!options.hasOwnProperty(key)) options[key] = defaultOptions[key]; } this.options = options; } else { this.options = defaultOptions; } this.armazenamento = {}; this.version = require('strong-db/package').version; let stats; try { stats = fs.statSync(filePath); } catch (err) { if (err.code === 'ENOENT') { return; } else if (err.code === 'EACCES') { throw new Error(`Não consigo acessar o Arquivo: "${filePath}".`); } else { throw new Error(`Erro detectado! "${filePath}": ${err}`); } } try { fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK); } catch (err) { throw new Error(`Eu não consigo Ver e nem Editar o JSON: "${filePath}".`); } if (stats.size > 0) { let data; try { data = fs.readFileSync(filePath); } catch (err) { throw err; } if (validateJSON(data)) this.armazenamento = JSON.parse(data); } } StrongDB.prototype.set = function StrongDbSet(key, value) { if(!key) new Error('Coloque o Caminho.'); if(!value) new Error('Coloque o Valor.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} object.set(data, key, value) this.armazenamento = data; if (this.options && this.options.edit) this.sync(); return true; }; StrongDB.prototype.get = function StrongDbGet(key) { if(!key) new Error('Coloque o Caminho.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} let value = object.get(data, key); if(!value) value = null; return value; }; StrongDB.prototype.all = function StrongDbAll(key = '/') { let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} return object.get(data, key); }; StrongDB.prototype.leaderboard = function StrongDbLeaderboard(key = '/') { let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} let meuSet = [] let array = Array.from(Object.keys(object.get(data, key))) array.map(async e => { var info = { id: e, values: object.get(data, key)[e] || 0 } await meuSet.push(info) }) return meuSet; }; StrongDB.prototype.add = function StrongDbGet(key, value) { if(!key) new Error('Coloque o Caminho.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} let val = object.get(data, key) || 0; if(typeof val !== 'number') throw new Error('A função Add só é válida para dados em formato de NUMBER'); if(!value) new Error('Coloque o Valor para Adicionar.'); object.set(data, key, Number(val) + Number(value)) this.armazenamento = data; if (this.options && this.options.edit) this.sync(); return true; }; StrongDB.prototype.sub = function StrongDbGet(key, value) { if(!key) new Error('Coloque o Caminho.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} let val = object.get(data, key) || 0; if(typeof val !== 'number') throw new Error('A função Sub só é válida para dados em formato de NUMBER'); if(!value) new Error('Coloque o Valor para Subtrair.'); object.set(data, key, Number(val) - Number(value)) this.armazenamento = data; if (this.options && this.options.edit) this.sync(); return true; }; StrongDB.prototype.typeOf = function StrongDbTypeOf(key) { if(!key) new Error('Coloque o Caminho.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} let value = object.get(data, key); if(!value) value = null; return typeof value; }; StrongDB.prototype.has = function StrongDbHas(key) { if(!key) new Error('Coloque o Caminho.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} return object.has(data, key) }; StrongDB.prototype.delete = function StrongDbDelete(key) { if(!key) new Error('Coloque o Caminho.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} object.delete(data, key) this.armazenamento = data; if (this.options && this.options.edit) this.sync(); return true; }; StrongDB.prototype.ping = async function StrongDbPing() { let date = Date.now(); let pingDb = await this.armazenamento['ping'] pingDb = Date.now() - date + Math.floor(Math.random() * 2) + 2 * 2 return pingDb; }; StrongDB.prototype.push = function StrongDbPush(array, value) { if(!array) new Error('Coloque o Caminho do Array.'); if(!value) new Error('Coloque o Valor.'); if(typeof array !== 'object') new Error('So é possivél dar Push em Array.'); let data = JSON.parse(JSON.stringify(this.armazenamento)) || {} object.push(data, array, value); this.armazenamento = data; if (this.options && this.options.edit) this.sync(); return true; }; StrongDB.prototype.sync = function() { try { fs.writeFileSync(this.filePath, JSON.stringify(this.armazenamento, null, 4)); } catch (err) { if (err.code === 'EACCES') { throw new Error(`Sem acesso ao Arquivo: "${this.filePath}".`); } else { throw new Error(`Erro ao editar o arquivo: "${this.filePath}": ${err}`); } } }; module.exports = StrongDB;