Reputation: 190
For example, I have entities like Photo, Company, Car, etc. I know that they have columns with same names and I can access it via QueryBuilder. I don't know which repository I will process, but it's passed like string parameter to my function. Like this:
function haveAccess(user, entity, entityId) {
// model is string like 'photo', 'company', 'car'
}
In fact, I want to check if user have access to the entity with given ID via separate function not binded to just one Entity.
Is it possible to initialize Repository or QueryBuilder for Entity in TypeORM just by string somehow?
Upvotes: 4
Views: 3710
Reputation: 3694
You can get repositories like this:
import {getRepository} from "typeorm";
import {User} from "./entity/User";
const userRepository = getRepository(User); // you can also get it via getConnection().getRepository() or getManager().getRepository()
connection.getRepository()
can take three things, an Object (annotated with @Entity
), an EntitySchema, or a string.
getRepository<Entity>(target: ObjectType<Entity> | EntitySchema<Entity> | string): Repository<Entity>;
So in typescript that could be:
connection.getRepository<MyEntity>(MyEntity)
Upvotes: 2