add mysql db #54

Open
mengguyi wants to merge 3 commits from mengguyi/master into master
5 changed files with 75 additions and 2092 deletions
Showing only changes of commit cc53fb551b - Show all commits

View File

@ -2,4 +2,4 @@ app:
port: 3000
db:
type: mongodb # sqlite or mongodb
type: sqlite # sqlite or mongodb or mysql

View File

@ -8,6 +8,9 @@ switch(config.db.type){
case 'mongodb':
db = require('./mongodb')
break;
case 'mysql':
db = require('./mysql')
break;
case 'sqlite':
default:
db = require('./sqlite')

70
db/mysql.js Normal file
View File

@ -0,0 +1,70 @@
'use strict'
const mysql = require('mysql2')
const mysqlURL = process.env.DB_URL || 'mysql://user:password@localhost:3306/database'
let hosts = mysqlURL.split("://")[1].split("/")[0];
let mysql_database = mysqlURL.split("://")[1].split("/")[1].split("?")[0];
let mysql_user = hosts.split("@")[0].split(":")[0];
let mysql_password = hosts.split("@")[0].split(":")[1];
let mysql_host = hosts.split("@")[1].split(":")[0];
let mysql_port = hosts.split("@")[1].split(":")[1];
const db = mysql.createPool({
host: mysql_host,
user: mysql_user,
password: mysql_password,
database: mysql_database,
port: mysql_port
})
db.query(`CREATE TABLE IF NOT EXISTS tb_count (
id INTEGER PRIMARY KEY AUTO_INCREMENT
NOT NULL
UNIQUE,
name VARCHAR (32) NOT NULL
UNIQUE,
num BIGINT NOT NULL
DEFAULT (0)
);`)
function getNum(name) {
return new Promise((resolve, reject) => {
db.query('SELECT `name`, `num` from tb_count WHERE `name` = ?', name, (err, rows) => {
if (err) reject(err)
resolve(rows[0] || { name, num: 0 })
})
})
}
function getAll(name) {
return new Promise((resolve, reject) => {
db.query('SELECT * from tb_count', (err, rows) => {
if (err) reject(err)
resolve(rows)
})
})
}
function setNum(name, num) {
return new Promise((resolve, reject) => {
db.query(`INSERT INTO tb_count(\`name\`, \`num\`)
VALUES(?, ?)
ON DUPLICATE KEY UPDATE \`num\` = ?;`
, [name, num, num]
, (err, result) => {
if (err) reject(err)
resolve(result)
})
})
}
module.exports = {
getNum,
getAll,
setNum
}

2091
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -17,6 +17,7 @@
"image-size": "^0.8.3",
"mime-types": "^2.1.27",
"mongoose": "^5.9.28",
"mysql2": "^3.3.5",
"pug": "^3.0.0",
"sqlite3": "^5.0.0"
}