forked from Shared/esg
database migrated to POSTGRESQL
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { Model, Types } from 'mongoose';
|
||||
import { User, UserDocument } from '../users/schemas/user.schema';
|
||||
import { DeepPartial, Repository } from 'typeorm';
|
||||
import { isUuid } from '../database/postgres.helpers';
|
||||
import { User } from '../users/schemas/user.schema';
|
||||
|
||||
type ExtendedJsonValue =
|
||||
| string
|
||||
@@ -14,7 +15,7 @@ type ExtendedJsonValue =
|
||||
| { [key: string]: ExtendedJsonValue };
|
||||
|
||||
interface SeedUser {
|
||||
_id?: Types.ObjectId;
|
||||
id?: string;
|
||||
fullName: string;
|
||||
username: string;
|
||||
email: string;
|
||||
@@ -32,7 +33,7 @@ interface SeedUser {
|
||||
requestLimitPerDay: number;
|
||||
totalRequests?: number;
|
||||
passwordChangedAt?: Date;
|
||||
createdBy?: Types.ObjectId;
|
||||
createdBy?: string | null;
|
||||
createdAt?: Date;
|
||||
updatedAt?: Date;
|
||||
lastLoginAt?: Date;
|
||||
@@ -44,7 +45,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
private readonly logger = new Logger(DatabaseSeederService.name);
|
||||
private readonly usersSeedFile = 'inquiry-gateway.users.json';
|
||||
|
||||
constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) {}
|
||||
constructor(@InjectRepository(User) private readonly users: Repository<User>) {}
|
||||
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
await this.seedUsers();
|
||||
@@ -52,12 +53,17 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
|
||||
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.userModel.exists({
|
||||
$or: [{ _id: user._id }, { username: user.username }, { email: user.email }],
|
||||
const existing = await this.users.findOne({
|
||||
where: [{ username: user.username }, { email: user.email }],
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
@@ -65,7 +71,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.userModel.create(user);
|
||||
await this.users.save(this.users.create(user as DeepPartial<User>));
|
||||
inserted += 1;
|
||||
}
|
||||
|
||||
@@ -77,8 +83,10 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
this.logger.log(`Baseline users already exist; skipped ${skipped} user(s).`);
|
||||
}
|
||||
|
||||
private loadSeedUsers(): SeedUser[] {
|
||||
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);
|
||||
@@ -92,27 +100,46 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
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 {
|
||||
...user,
|
||||
...(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 {
|
||||
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),
|
||||
];
|
||||
|
||||
const seedPath = candidates.find((candidate) => existsSync(candidate));
|
||||
if (!seedPath) {
|
||||
throw new Error(`Unable to find seed file: ${this.usersSeedFile}`);
|
||||
}
|
||||
|
||||
return seedPath;
|
||||
return candidates.find((candidate) => existsSync(candidate));
|
||||
}
|
||||
|
||||
private normalizeExtendedJson(value: ExtendedJsonValue): unknown {
|
||||
@@ -125,7 +152,7 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
}
|
||||
|
||||
if (typeof value.$oid === 'string') {
|
||||
return new Types.ObjectId(value.$oid);
|
||||
return value.$oid;
|
||||
}
|
||||
|
||||
if (typeof value.$date === 'string') {
|
||||
@@ -133,12 +160,13 @@ export class DatabaseSeederService implements OnApplicationBootstrap {
|
||||
}
|
||||
|
||||
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 {
|
||||
private isSeedUser(value: unknown): value is SeedUser & { _id?: string; createdBy?: string } {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user