Skip to content

Commit

Permalink
fix(adapter): json db change is made
Browse files Browse the repository at this point in the history
  • Loading branch information
vicente1992 committed Dec 21, 2022
1 parent 9ad4874 commit 3bdc7af
Show file tree
Hide file tree
Showing 3 changed files with 156 additions and 139 deletions.
3 changes: 1 addition & 2 deletions packages/database/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
49 changes: 33 additions & 16 deletions packages/database/src/json/index.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
}
}

Expand Down
Loading

0 comments on commit 3bdc7af

Please sign in to comment.