-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathdb.js
101 lines (91 loc) · 2.59 KB
/
db.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const sqlite3 = require('sqlite3').verbose();
let db;
function initializeDatabase() {
db = new sqlite3.Database('./apiKeys.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
if (err) {
console.error('Error connecting to the database:', err.message);
} else {
console.log('Connected to the apiKeys.db database.');
createTables();
}
});
return db;
}
// Function to create the tables even if they do not exist in the database
function createTables() {
db.run(`CREATE TABLE IF NOT EXISTS apiKeys (
key TEXT PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_used TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
tokens INTEGER DEFAULT 10,
rate_limit INTEGER DEFAULT 10,
active INTEGER DEFAULT 1,
description TEXT
)`, (err) => {
if (err) {
console.error('Error creating apiKeys table:', err.message);
}
});
db.run(`CREATE TABLE IF NOT EXISTS apiUsage (
key TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`, (err) => {
if (err) {
console.error('Error creating apiUsage table:', err.message);
}
});
db.run(`CREATE TABLE IF NOT EXISTS webhooks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL
)`, (err) => {
if (err) {
console.error('Error creating webhooks table:', err.message);
}
});
ensureColumns();
}
function ensureColumns() {
db.all("PRAGMA table_info(apiKeys)", (err, rows) => {
if (err) {
console.error('Error checking table info:', err.message);
} else {
const columns = rows.map(row => row.name);
if (!columns.includes('active')) {
db.run("ALTER TABLE apiKeys ADD COLUMN active INTEGER DEFAULT 1", (err) => {
if (err) {
console.error('Error adding active column:', err.message);
} else {
console.log("Added 'active' column to 'apiKeys' table.");
}
});
}
if (!columns.includes('description')) {
db.run("ALTER TABLE apiKeys ADD COLUMN description TEXT", (err) => {
if (err) {
console.error('Error adding description column:', err.message);
} else {
console.log("Added 'description' column to 'apiKeys' table.");
}
});
}
}
});
}
function closeDatabase() {
db.close((err) => {
if (err) {
console.error('Error closing the database connection:', err.message);
} else {
console.log('Closed the database connection.');
}
process.exit(0);
});
}
function getDb() {
return db;
}
module.exports = {
initializeDatabase,
closeDatabase,
getDb
};