Home > Back-end >  Generic repository typescript / router-controller API
Generic repository typescript / router-controller API

Time:04-14

'im trying to make a generic repository for my api but i'm stuck... how can i use a type as a string to select the right table ?

export default abstract class GenericRepository<T> {
    async getAll(): Promise<T[]> {
        try {
            const client = await db.connect();
            const res = await client.query<T>(`SELECT * FROM rant_${T.toString()}`); // <-- here
            client.release();
            return res.rows;
        } catch (error) {
            throw new InternalServerError('ERROR');
        }
    }
}

CodePudding user response:

You can't use a type as a value but you can make all child classes pass a name to the abstract class:

export default abstract class GenericRepository<T> {
    constructor(protected tableName: string) {}

    async getAll(): Promise<T[]> {
        try {
            const client = await db.connect();
            const res = await client.query<T>(`SELECT * FROM rant_${this.tableName}`); // <-- here
            client.release();
            return res.rows;
        } catch (error) {
            throw new InternalServerError('ERROR');
        }
    }
}

Extend it:

export default class UserRepository extends GenericRepository<User> {
     constructor() { super("users"); }

     // ...
}
  • Related