Closed punkish closed 3 months ago
Have you tried instanceof?
thanks. I think I know what is going on… my db connection is created in one file, and the plugin is in a different file like so
// file1.js
import Database from 'better-sqlite3';
const db = new Database('./path/to/db');
foo(db);
// file2.js
import Database from 'better-sqlite3';
function foo(option) {
let db;
if (option is a better-sqlite3 connection) { ← this is where I want help)
// do other things
}
else {
db = new Database('./path/to/db');
}
}
Because file2.js
has a different instance of Database
, the following evaluates to false
if (options instanceof Database) { ← evaluates to false
// do other things
}
else {
db = new Database('./path/to/db');
}
The following seems to work but I am not sure if it is the right way to test
if (options.__proto__.constructor.name === 'Database') { ← evaluates to true
// do other things
}
else {
db = new Database('./path/to/db');
}
To my knowledge that would be the best that you can get as the problem is not related to better-sqlite3 but the used programming language and runtime environment we are tied to here.
You might be able to attach some arbitrary value to a Database instance like
const db = new Database('./path/to/db');
db.valueOnlyIKnowAbout = 'Something'
and check for that, but in the end you won't get better than the things JavaScript and the interpretation environment will offer you.
I am writing a plugin wherein the user can pass in a readymade better-sqlite3 connection as an option. I want to test if the passed in option is indeed a better-sqlite3 connection. If it is, we work with it. If not, we create a new connection for the user. How can I do this? That is, how can I identify a passed in option to be a better-sqlite3 connection? consider simplified code like so