Skip to content

Instantly share code, notes, and snippets.

@framp
Created November 23, 2022 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save framp/48d3b39cc3a34329ac51b1e4a43d36d4 to your computer and use it in GitHub Desktop.
Save framp/48d3b39cc3a34329ac51b1e4a43d36d4 to your computer and use it in GitHub Desktop.
Look ma', no dependency injection
const EventEmitter = require("events");
const sqlite3 = require("sqlite3");
const { open } = require("sqlite");
sqlite3.verbose();
let instance = {};
const status = new EventEmitter();
status.started = false;
const db = new Proxy(
{},
{
get(_target, prop) {
if (status.started) {
return instance[prop];
}
return async (...args) => {
await new Promise((res) => status.on("started", res));
return instance[prop].call(instance, ...args);
};
},
},
);
(async () => {
instance = await open({
filename: process.env.DATABASE_URL || "app.db",
driver: sqlite3.Database,
});
await instance.migrate();
status.started = true;
status.emit("started");
})();
module.exports = db;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment