feat: Add seeder module and services for all lookup tables

This commit is contained in:
faris Aljohari
2024-05-18 21:53:27 +03:00
parent 50a3d8ee49
commit ad15164e15
10 changed files with 233 additions and 28 deletions

View File

@ -0,0 +1,72 @@
import { Injectable } from '@nestjs/common';
import { UserRepository } from '@app/common/modules/user/repositories';
import { RoleType } from '@app/common/constants/role.type.enum';
import { UserRoleRepository } from '@app/common/modules/user-role/repositories';
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
import { ConfigService } from '@nestjs/config';
import { HelperHashService } from '../../helper/services';
@Injectable()
export class SuperAdminSeeder {
constructor(
private readonly configService: ConfigService,
private readonly userRepository: UserRepository,
private readonly userRoleRepository: UserRoleRepository,
private readonly roleTypeRepository: RoleTypeRepository,
private readonly helperHashService: HelperHashService,
) {}
async createSuperAdminIfNotFound(): Promise<void> {
try {
const superAdminData = await this.userRoleRepository.find({
where: { roleType: { type: RoleType.SUPER_ADMIN } },
relations: ['roleType'],
});
if (superAdminData.length <= 0) {
// Create the super admin user if not found
console.log('Creating super admin user...');
await this.createSuperAdmin();
}
} catch (err) {
console.error('Error while checking super admin:', err);
throw err;
}
}
private async getRoleUuidByRoleType(roleType: string) {
const role = await this.roleTypeRepository.findOne({
where: { type: roleType },
});
return role.uuid;
}
private async createSuperAdmin(): Promise<void> {
const salt = this.helperHashService.randomSalt(10); // Hash the password using bcrypt
const hashedPassword = await this.helperHashService.bcrypt(
this.configService.get<string>('super-admin.SUPER_ADMIN_PASSWORD'),
salt,
);
try {
const user = await this.userRepository.save({
email: this.configService.get<string>('super-admin.SUPER_ADMIN_EMAIL'),
password: hashedPassword,
firstName: 'Super',
lastName: 'Admin',
isUserVerified: true,
isActive: true,
});
const defaultUserRoleUuid = await this.getRoleUuidByRoleType(
RoleType.SUPER_ADMIN,
);
await this.userRoleRepository.save({
user: { uuid: user.uuid },
roleType: { uuid: defaultUserRoleUuid },
});
} catch (err) {
console.error('Error while creating super admin:', err);
throw err;
}
}
}