iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦔
Custom SQLite Module Template for Express
Custom Module File for Using SQLite in an Express Project
To allow checking logs and queries, and to toggle them off as needed.
database.js
// Import module "sqlite3"
const sqlite3 = require("sqlite3");
// Toggle whether to display logs here; it might be better to use environment variables.
const ADVANCED_LOG = false;
// List of database file paths
module.exports.LS = {};
// Initialize
// Returns a DatabaseHandler with the file path as an argument
module.exports.init = (file) => {
return new DatabaseHandler(file);
}
//
class DatabaseHandler {
constructor (databaseFile) {
this.file = databaseFile;
this.database = new sqlite3.Database(databaseFile);
console.log(`SQLite[Load] "${databaseFile}"`);
}
get(query, bindValues, callback = ()=>{}){
console.log(`SQLite.Get > "${query}"\n> `, bindValues);
this.database.get(query, bindValues, (err, row) => {
if (ADVANCED_LOG) console.log("SQLite.Result > ", row);
if (ADVANCED_LOG && err) console.log("SQLite.Result.Err > ", err);
callback(err, row);
});
}
all(query, bindValues, callback = ()=>{}){
console.log(`SQLite.All > "${query}"\n> `, bindValues);
this.database.all(query, bindValues, (err, rows) => {
if (ADVANCED_LOG) console.log("SQLite.Result > ", rows);
if (ADVANCED_LOG && err) console.log("SQLite.Result.Err > ", err);
callback(err, rows);
});
}
run(query, bindValues, callback = ()=>{}){
console.log(`SQLite.Run > "${query}"\n> `, bindValues);
this.database.run(query, bindValues, (err) => {
if (ADVANCED_LOG && err) console.log("SQLite.Result.Err > ", err);
callback(err);
});
}
serialize(func){
console.log(`SQLite.Serialize --- BEGIN ---`);
this.database.serialize(func);
}
close(errorHandler = (err) => {}){
console.log(`SQLite[Close] "${this.file}"`);
if (errorHandler === undefined) {
this.database.close(err => { if (err) console.error(err); });
} else {
this.database.close(errorHandler);
}
}
}
Usage
sample.js
const database = require("./database.js");
const db = database.init(database.LS.USERS);
db.get("", () => {}); ....
Discussion