Creating my own MySQL ORM for a project. I have designed an abstract 'model' class that other models I develop can inherit from, inheriting all their methods and properties. My current challenge revolves around specifying that a method will return the type of the class that extends it. Below is some code snippet.
import db from '../db'
export default abstract class Model {
protected static TableName: string
protected static Columns: string[]
protected constructor() {
console.log('Initializing a model')
}
//Replace Model here with something like "type of this"
public static async findByID(id: string): Promise<Model> {
const query = `select ${this.columns} from ${db.name}.${this.TableName} where ${this.Columns[0]}='${id}'`
return (await db.query(query) as Model[])[0] //Replace Model here with something like "type of this"
}
private static get columns(): string {
return this.Columns.reduce((acc, cur, i, arr) => i !== arr.length - 1 ? acc + cur + ', ' : acc + cur, '')
}
}
I acknowledge the risk of potential SQL injection. Thanks!