I'm trying to implement a lazy database connection collection in typescript. I'm creating a class called DatabaseCollection and my idea is to use a proxy to lazy load the connections (I'm using knex as connector) the class works fine in terms of node context, but Typescript says "property does not exists" and I don't know how to tell to Typescript about a dynamic properties class.
I use a workaround converting to Record<string, Knex> but I want to implement it properly, thanks in advance.
Here is the code:
const debug = true
process.env['DB_TEST_URL'] = 'mysql://root@localhost/test';
class NotImportantConnector {
public url: string;
constructor(url: string) {
this.url = url;
}
}
function dbFromURL(url: string): NotImportantConnector {
return new NotImportantConnector(url);
}
class DatabasesCollection<T> {
protected databases: Record<string, T> = {};
constructor() {
return new Proxy(this, this) as any;
}
get (target: DatabasesCollection<T>, name: string): T {
if (name in target.databases) {
return target.databases[name];
}
const envName = `DB_${name.replace(/[A-Z]/g, l => `_${l}`).toUpperCase()}_URL`;
if (!process.env[envName]) {
throw new Error(`Call to database ${name} needs ${envName} environment variable to run`);
}
target.databases[name] = dbFromURL(process.env[envName] as string) as T;
return target.databases[name];
}
}
// Not working with error Property 'test' does not exist on type 'DatabasesCollection<NotImportantConnector>'.
// const db = new DatabasesCollection<NotImportantConnector>();
// Workaround, using as
const db = new DatabasesCollection<NotImportantConnector>() as unknown as Record<string, NotImportantConnector>;
console.log(db.test);
process(that's node specific, right?) ordbFromURLorKnexin scope. It would be helpful if you'd either define/import them (and if importing, tag the question with appropriate dependencies), or even better: replace them with native things. Anything that makes it easier for others to get immediately to work on the issue will make it more likely you get a useful answer.