forked from memberapp/server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbhandler.js
64 lines (60 loc) · 2.21 KB
/
dbhandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Copyright (C) 2019-present FreeTrade
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3.0
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see
* <https://www.gnu.org/licenses/agpl-3.0.en.html>.
*
*/
'use strict';
var dbhandler = {};
var util = require('util'); //for promisify
dbhandler.createPool = async function (dbtype, options) {
if (dbtype == 'mysql') {
var mysql = require('mysql');
var pool = mysql.createPool(options);
pool.runQuery = util.promisify(pool.query).bind(pool);
pool.asyncgetConnection = util.promisify(pool.getConnection).bind(pool);
} else if (dbtype == 'sqlite') {
//nb not really a pool
var sqlite = require('sqlite-async');
//Copy the schema if the db doesn't exist yet
var fs = require('fs');
if (!fs.existsSync(options.sqldbfile)) {
await fs.createReadStream(options.schemafile).pipe(fs.createWriteStream(options.sqldbfile));
await sleep(1000); //seem to need to wait for a bit before accessing this copied file
}
var pool = await sqlite.open(options.sqldbfile);
pool.runQuery=pool.all;
}
return pool;
}
dbhandler.getConnection = async function (dbtype, dbpool){
if (dbtype == 'mysql') {
var conn = await dbpool.asyncgetConnection();
conn.runQuery = util.promisify(conn.query).bind(conn);
return conn;
} else if (dbtype = 'sqlite') {
return dbpool;
}
}
/*
dbhandler.runQuery = async function (dbtype, pool, sql) {
if (dbtype == 'mysql') {
return await pool.runQuery(sql);
} else if (dbtype == 'sqlite') {
return await pool.runQuery(sql);
}
}*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
module.exports = dbhandler;