Repository navigation
Expand file tree
/
Copy pathdb.js
More file actions
44 lines (39 loc) · 1.3 KB
/
Copy pathdb.js
File metadata and controls
44 lines (39 loc) · 1.3 KB
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
// Drop-in MySQL connection shim backed by SQLite (better-sqlite3)
const Database = require('better-sqlite3');
const path = require('path');
const db = new Database(path.join(__dirname, 'selink.db'));
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(100) NOT NULL,
is_superuser INTEGER NOT NULL DEFAULT 0,
password VARCHAR(255) NOT NULL
);
`);
// Seed default root:123 account if table is empty
const count = db.prepare('SELECT COUNT(*) as c FROM users').get();
if (count.c === 0) {
db.prepare('INSERT INTO users (username, is_superuser, password) VALUES (?, ?, ?)').run(
'root', 1, '$2b$10$Vpkyqp3T52vC54ul0BLCJutZjNzOTUpXA0KrnQL6fetaPfOSTUYv6'
);
}
const connection = {
connect: (cb) => cb(null),
query: (sql, params, cb) => {
if (typeof params === 'function') { cb = params; params = []; }
if (!Array.isArray(params)) params = [params];
try {
const stmt = db.prepare(sql);
const upper = sql.trim().toUpperCase();
if (upper.startsWith('SELECT')) {
cb(null, stmt.all(...params));
} else {
const info = stmt.run(...params);
cb(null, { affectedRows: info.changes, insertId: info.lastInsertRowid });
}
} catch (e) {
cb(e, null);
}
}
};
module.exports = connection;