43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
import type { EntityManager } from '@mikro-orm/core';
|
|
import { Admin } from '../modules/admin/entities/admin.entity';
|
|
import { AdminRole } from '../modules/admin/entities/adminRole.entity';
|
|
import type { Role } from '../modules/roles/entities/role.entity';
|
|
import type { Restaurant } from '../modules/restaurants/entities/restaurant.entity';
|
|
import { adminsData } from './data/admins.data';
|
|
import { normalizePhone } from '../modules/utils/phone.util';
|
|
|
|
export class AdminsSeeder {
|
|
async run(em: EntityManager, rolesMap: Map<string, Role>, restaurantsMap: Map<string, Restaurant>): Promise<void> {
|
|
for (const adminData of adminsData) {
|
|
const existingAdmin = await em.findOne(Admin, { phone: adminData.phone });
|
|
if (existingAdmin) continue;
|
|
|
|
const role = rolesMap.get(adminData.roleName);
|
|
if (!role) continue;
|
|
|
|
const restaurant = adminData.restaurantSlug ? restaurantsMap.get(adminData.restaurantSlug) : null;
|
|
|
|
// For restaurant role, restaurant is required
|
|
if (!restaurant) continue;
|
|
|
|
const admin = em.create(Admin, {
|
|
phone: normalizePhone(adminData.phone),
|
|
firstName: adminData.firstName,
|
|
lastName: adminData.lastName,
|
|
});
|
|
em.persist(admin);
|
|
|
|
// Create AdminRole linking admin to role and restaurant
|
|
const adminRole = em.create(AdminRole, {
|
|
admin,
|
|
role,
|
|
restaurant: adminData.restaurantSlug ? restaurant : null,
|
|
});
|
|
em.persist(adminRole);
|
|
admin.roles.add(adminRole);
|
|
}
|
|
|
|
await em.flush();
|
|
}
|
|
}
|