forked from Shared/esg
188 lines
5.5 KiB
TypeScript
188 lines
5.5 KiB
TypeScript
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { existsSync, readFileSync } from 'fs';
|
|
import { join } from 'path';
|
|
import { DeepPartial, Repository } from 'typeorm';
|
|
import { isUuid } from '../database/postgres.helpers';
|
|
import { User } from '../users/schemas/user.schema';
|
|
|
|
type ExtendedJsonValue =
|
|
| string
|
|
| number
|
|
| boolean
|
|
| null
|
|
| ExtendedJsonValue[]
|
|
| { [key: string]: ExtendedJsonValue };
|
|
|
|
interface SeedUser {
|
|
id?: string;
|
|
fullName: string;
|
|
username: string;
|
|
email: string;
|
|
mobile?: string;
|
|
password: string;
|
|
role: string;
|
|
clientType: string;
|
|
appName: string;
|
|
clientName: string;
|
|
isActive: boolean;
|
|
isBlocked: boolean;
|
|
apiKey?: string;
|
|
allowedInquiries: string[];
|
|
requestLimitPerMinute: number;
|
|
requestLimitPerDay: number;
|
|
totalRequests?: number;
|
|
passwordChangedAt?: Date;
|
|
createdBy?: string | null;
|
|
createdAt?: Date;
|
|
updatedAt?: Date;
|
|
lastLoginAt?: Date;
|
|
refreshToken?: string;
|
|
}
|
|
|
|
@Injectable()
|
|
export class DatabaseSeederService implements OnApplicationBootstrap {
|
|
private readonly logger = new Logger(DatabaseSeederService.name);
|
|
private readonly usersSeedFile = 'inquiry-gateway.users.json';
|
|
|
|
constructor(@InjectRepository(User) private readonly users: Repository<User>) {}
|
|
|
|
async onApplicationBootstrap(): Promise<void> {
|
|
await this.seedUsers();
|
|
}
|
|
|
|
private async seedUsers(): Promise<void> {
|
|
const users = this.loadSeedUsers();
|
|
if (!users) {
|
|
this.logger.warn(`Seed file ${this.usersSeedFile} not found; skipping baseline user seed.`);
|
|
return;
|
|
}
|
|
|
|
let inserted = 0;
|
|
let skipped = 0;
|
|
|
|
for (const user of users) {
|
|
const existing = await this.users.findOne({
|
|
where: [{ username: user.username }, { email: user.email }],
|
|
});
|
|
|
|
if (existing) {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
|
|
await this.users.save(this.users.create(user as DeepPartial<User>));
|
|
inserted += 1;
|
|
}
|
|
|
|
if (inserted > 0) {
|
|
this.logger.log(`Seeded ${inserted} baseline user(s); skipped ${skipped} existing user(s).`);
|
|
return;
|
|
}
|
|
|
|
this.logger.log(`Baseline users already exist; skipped ${skipped} user(s).`);
|
|
}
|
|
|
|
private loadSeedUsers(): SeedUser[] | null {
|
|
const seedPath = this.resolveSeedPath();
|
|
if (!seedPath) return null;
|
|
|
|
const raw = readFileSync(seedPath, 'utf8');
|
|
const parsed = JSON.parse(raw) as ExtendedJsonValue;
|
|
const normalized = this.normalizeExtendedJson(parsed);
|
|
|
|
if (!Array.isArray(normalized)) {
|
|
throw new Error(`${this.usersSeedFile} must contain an array of users`);
|
|
}
|
|
|
|
return normalized.map((user) => {
|
|
if (!this.isSeedUser(user)) {
|
|
throw new Error(`${this.usersSeedFile} contains an invalid user document`);
|
|
}
|
|
|
|
const rawId = (user as SeedUser & { _id?: string })._id ?? user.id;
|
|
const id = typeof rawId === 'string' && isUuid(rawId) ? rawId : undefined;
|
|
const createdBy = typeof user.createdBy === 'string' && isUuid(user.createdBy) ? user.createdBy : null;
|
|
|
|
return {
|
|
...(id ? { id } : {}),
|
|
fullName: user.fullName,
|
|
username: user.username.toLowerCase().trim(),
|
|
email: user.email.toLowerCase().trim(),
|
|
mobile: user.mobile,
|
|
password: user.password,
|
|
role: user.role,
|
|
clientType: user.clientType,
|
|
appName: user.appName ?? '',
|
|
clientName: user.clientName ?? '',
|
|
isActive: user.isActive,
|
|
isBlocked: user.isBlocked,
|
|
apiKey: user.apiKey,
|
|
allowedInquiries: user.allowedInquiries,
|
|
requestLimitPerMinute: user.requestLimitPerMinute,
|
|
requestLimitPerDay: user.requestLimitPerDay,
|
|
totalRequests: user.totalRequests ?? 0,
|
|
passwordChangedAt: user.passwordChangedAt,
|
|
createdBy,
|
|
createdAt: user.createdAt,
|
|
updatedAt: user.updatedAt,
|
|
lastLoginAt: user.lastLoginAt,
|
|
refreshToken: user.refreshToken,
|
|
};
|
|
});
|
|
}
|
|
|
|
private resolveSeedPath(): string | undefined {
|
|
const candidates = [
|
|
join(__dirname, 'seeds', this.usersSeedFile),
|
|
join(process.cwd(), 'src', 'database', 'seeds', this.usersSeedFile),
|
|
join(process.cwd(), 'dist', 'database', 'seeds', this.usersSeedFile),
|
|
];
|
|
|
|
return candidates.find((candidate) => existsSync(candidate));
|
|
}
|
|
|
|
private normalizeExtendedJson(value: ExtendedJsonValue): unknown {
|
|
if (Array.isArray(value)) {
|
|
return value.map((item) => this.normalizeExtendedJson(item));
|
|
}
|
|
|
|
if (value === null || typeof value !== 'object') {
|
|
return value;
|
|
}
|
|
|
|
if (typeof value.$oid === 'string') {
|
|
return value.$oid;
|
|
}
|
|
|
|
if (typeof value.$date === 'string') {
|
|
return new Date(value.$date);
|
|
}
|
|
|
|
return Object.entries(value).reduce<Record<string, unknown>>((acc, [key, child]) => {
|
|
if (key === '__v') return acc;
|
|
acc[key] = this.normalizeExtendedJson(child);
|
|
return acc;
|
|
}, {});
|
|
}
|
|
|
|
private isSeedUser(value: unknown): value is SeedUser & { _id?: string; createdBy?: string } {
|
|
if (!value || typeof value !== 'object') {
|
|
return false;
|
|
}
|
|
|
|
const user = value as Partial<SeedUser>;
|
|
return (
|
|
typeof user.fullName === 'string' &&
|
|
typeof user.username === 'string' &&
|
|
typeof user.email === 'string' &&
|
|
typeof user.password === 'string' &&
|
|
typeof user.role === 'string' &&
|
|
typeof user.clientType === 'string' &&
|
|
Array.isArray(user.allowedInquiries) &&
|
|
typeof user.requestLimitPerMinute === 'number' &&
|
|
typeof user.requestLimitPerDay === 'number'
|
|
);
|
|
}
|
|
}
|