Sometimes I need to use typeorm, sequelize or mongoose. I want to set up a solid structure that I can use in every project.
For example,
Typeorm Model Defining:
@Entity()
class UserTO {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
email: string;
@Column()
password: string;
}
Sequelize Model Defining:
const User = sequelize.define('User', {
firstName: { type: DataTypes.STRING, },
lastName: { type: DataTypes.STRING}}, {
});
I want make like this:
class User implements Model {
id: number;
firstName: string;
lastName: string;
}
interface IRepository<T> {
// T is model
add(entity: T): void;
delete(entity: T): void;
update(entity: T): void;
getAll(filter?: object): T[];
getOne(filter: object): T;
}
class TypeOrmBaseRepository<T> implements IRepository<T> {
add(entity: T): void {
// database operations with typeorm
}
delete(entity: T): void {
// database operations with typeorm
}
update(entity: T): void {
// database operations with typeorm
}
getAll(filter?: object): T[]{
// database operations with typeorm
}
getOne(filter: object): T {
// database operations with typeorm
}
}
class SequelizeBaseRepository<T> implements IRepository<T> {
add(entity: T): void {
// database operations with sequelize
}
delete(entity: T): void {
// database operations with sequelize
}
update(entity: T): void {
// database operations with sequelize
}
getAll(filter?: object): T[]{
// database operations with sequelize
}
getOne(filter: object): T {
// database operations with sequelize
}
}
class UserService {
private repository;
constructor(repository: IRepository) {
this.repository = repository
// Whatever ORM's concrete object I give it will work according to what I gave it.
}
// Service codes
}
Is it possible to make such a structure? I have not seen such a structure in many projects I have reviewed.