feat(adapter): added adapter mysql

This commit is contained in:
vicente1992
2022-12-02 09:41:57 -05:00
parent 7d41699207
commit 717a7dc95f
4 changed files with 612 additions and 417 deletions

View File

@@ -9,10 +9,12 @@
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.3",
"mongodb": "^4.11.0"
"mongodb": "^4.11.0",
"mysql2": "^2.3.3"
},
"exports": {
"./mock": "./lib/mock/index.cjs",
"./mongo": "./lib/mongo/index.cjs"
"./mongo": "./lib/mongo/index.cjs",
"./mysql": "./lib/mysql/index.cjs"
}
}

View File

@@ -21,4 +21,13 @@ module.exports = [
},
plugins: [commonjs()],
},
{
input: join(__dirname, 'src', 'mysql', 'index.js'),
output: {
banner: banner['banner.output'].join(''),
file: join(__dirname, 'lib', 'mysql', 'index.cjs'),
format: 'cjs',
},
plugins: [commonjs()],
},
]

View File

@@ -0,0 +1,76 @@
require('dotenv').config()
const mysql = require('mysql2')
const DB_NAME = process.env.DB_NAME || 'db_bot'
const DB_HOST = process.env.DB_HOST || 'localhost'
const DB_USER = process.env.DB_USER || 'root'
class MyslAdapter {
db
listHistory = []
constructor() {
this.init().then()
}
async init() {
this.db = mysql.createConnection({
host: DB_HOST,
user: DB_USER,
database: DB_NAME,
})
await this.db.connect((error) => {
if (!error) {
console.log(`Solicitud de conexión a base de datos exitosa`)
}
if (error) {
console.log(`Solicitud de conexión fallida ${error.stack}`)
}
})
}
getPrevByNumber = (from) =>
new Promise((resolve, reject) => {
const sql = `SELECT * FROM history WHERE phone=${from} ORDER BY id DESC`
this.db.query(sql, (error, rows) => {
if (error) {
reject(error)
}
if (rows.length) {
const [row] = rows
row.options = JSON.parse(row.options)
resolve(row)
}
if (!rows.length) {
resolve(null)
}
})
})
save = (ctx) => {
const values = [
[
ctx.ref,
ctx.keyword,
ctx.answer,
ctx.refSerialize,
ctx.from,
JSON.stringify(ctx.options),
],
]
const sql =
'INSERT INTO history (ref, keyword, answer, refSerialize, phone, options ) values ?'
this.db.query(sql, [values], (err) => {
if (err) throw err
console.log('Guardado en DB...', values)
})
this.listHistory.push(ctx)
}
}
module.exports = MyslAdapter

938
yarn.lock

File diff suppressed because it is too large Load Diff