Cannot read property 'typeCast' of undefined mysql
I found a different solution to the same problem. I haven't tested your code with this, but looking at the source code of the mysql module, in my case this
was no longer correct. Binding query
to the db object fixes it for me. In your case that would look like this:
this.query = promisify(this.db.query.bind(this.db));
Promisify(...)
returns a promise. So you should use await
like so: await Promisify(...)
The solution would be:
1) Remove the this.query = promisify(...)
and this.db.connect();
lines from your constructor
2) Your Database
class and getUser
functions should look like this:
export default class Database {
static instance: Database;
static async getInstance(user?, password?, database?, host?) {
// all arguments above are optional
if(!Database.instance){
const connection = createConnection({ user, password, database, host });
await connection.connect();
const dbQuery = await promisify(this.promisify(connection.query));
Database.instance = {
query: dbQuery
}
return Database.instance;
}
return Database.instance;
}
static getUser(id: number, filter: string = null) {
return Database.instance.query('SELECT * FROM users WHERE id = ' + id)
.then((err, res, fields) => {
return res[0];
});
}
}
To use:
Then, wherever you need:
async getUser(){
let database = await Database.getInstance(); // or Database.getInstance(user, password ...) to first initialize and then get the instance.
return database.getUser(1234, filter);
}