Created
November 23, 2022 14:59
-
-
Save framp/48d3b39cc3a34329ac51b1e4a43d36d4 to your computer and use it in GitHub Desktop.
Look ma', no dependency injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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