fix(adapter): json db change is made

This commit is contained in:
vicente1992
2022-12-20 22:21:41 -05:00
parent 9ad4874fda
commit 3bdc7afe80
3 changed files with 156 additions and 139 deletions

View File

@@ -12,8 +12,7 @@
"dependencies": {
"dotenv": "^16.0.3",
"mongodb": "^4.11.0",
"mysql2": "^2.3.3",
"stormdb": "^0.6.0"
"mysql2": "^2.3.3"
},
"exports": {
"./mock": "./lib/mock/index.cjs",

View File

@@ -1,27 +1,42 @@
const StormDB = require('stormdb')
const { join } = require('path')
const engine = new StormDB.localFileEngine(join(process.cwd(), './db.stormdb'))
const { existsSync, writeFileSync, readFileSync } = require('fs')
class JsonFileAdapter {
db
pathFile
listHistory = []
constructor() {
this.pathFile = join(process.cwd(), 'db.json')
this.init().then()
}
init() {
return new Promise((resolve) => {
this.db = new StormDB(engine)
this.db.default({ history: [] })
resolve(this.db)
})
databaseExists() {
return existsSync(this.pathFile)
}
async init() {
const dbExists = await this.databaseExists()
if (!dbExists) {
const data = {
history: [],
}
await this.saveData(data)
}
}
readDatabase() {
const db = readFileSync(this.pathFile)
return JSON.parse(db)
}
saveData(data) {
writeFileSync(this.pathFile, JSON.stringify(data))
}
getPrevByNumber = async (from) => {
const response = await this.db.get('history')
const { history } = response.state
const { history } = await this.readDatabase()
if (!history.length) {
return null
@@ -35,12 +50,14 @@ class JsonFileAdapter {
}
save = async (ctx) => {
await this.db
.get('history')
.push({ ...ctx })
.save()
console.log('Guardado en DB...', ctx)
this.db = await this.readDatabase()
this.db.history.push(ctx)
await this.saveData(this.db)
this.listHistory.push(ctx)
console.log('Guardado en DB...', ctx)
}
}