This commit is contained in:
wayanrivan
2026-03-30 10:18:13 +07:00
parent 9a39c89dd9
commit be2d11fbbd

View File

@ -1,84 +1,14 @@
// import config from 'config';
// import { DataSource } from "typeorm";
// import { ILogObj, Logger } from 'tslog';
// import { FareType, RoomStock, Administrativu, Aldeia, District, Menu, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift, HospitalInformation, ItemOrigin, ItemType, ItemTypeDetail, Unit, ItemCategory, ItemStatus, UsageInstructions, UsageTime, ItemClass, ItemClassDetail, GenericName, Factory, Supplier, FactoryToSupplier, ItemMaster, ItemGroup, PharmacyInfo, ItemPrice, SellingPricePercentage, PatientGroup, PatientGuarantor, InitialStock, DoctorItem, DoctorItemPackage, UserToRoom, RoomToPharmacy, PlanningVerificator, ScheduleSeries, ScheduleException, CardType, PaymentMethod } from 'entity'
// export class OrmHelper {
// static DB: DataSource = null
// static setup() {
// const log: Logger<ILogObj> = new Logger({ name: '[OrmHelper]', type: 'pretty' });
// const engine: 'mysql' | 'postgres' = config.get("database.engine")
// OrmHelper.DB = new DataSource({
// type: engine,
// host: config.get("database.host"),
// port: Number(config.get("database.port")),
// username: String(config.get("database.username")),
// password: String(config.get("database.password")),
// database: String(config.get("database.database")),
// synchronize: true,
// logging: config.get('database.logging'),
// entities: [Menu, Administrativu, Aldeia, District, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift, HospitalInformation, ItemGroup,
// ItemOrigin,
// ItemType,
// ItemTypeDetail,
// Unit,
// ItemCategory,
// ItemStatus,
// UsageInstructions,
// UsageTime,
// ItemClass,
// ItemClassDetail,
// GenericName,
// Factory,
// Supplier,
// FactoryToSupplier,
// ItemMaster,
// PharmacyInfo,
// ItemPrice,
// SellingPricePercentage,
// PatientGroup,
// PatientGuarantor,
// InitialStock,
// DoctorItem,
// DoctorItemPackage,
// UserToRoom,
// RoomToPharmacy,
// PlanningVerificator,
// RoomStock,
// ScheduleSeries,
// ScheduleException,
// FareType,
// CardType,
// PaymentMethod
// ],
// subscribers: [],
// migrations: [],
// })
// OrmHelper.DB.initialize()
// .then(() => {
// // here you can start to work with your database
// })
// .catch((error: any) => log.error(error))
// }
// }
import config from 'config'; import config from 'config';
import { DataSource } from "typeorm"; import { DataSource } from "typeorm";
import { ILogObj, Logger } from 'tslog'; import { ILogObj, Logger } from 'tslog';
import { FareType, RoomStock, Administrativu, Aldeia, District, Menu, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift, HospitalInformation, ItemOrigin, ItemType, ItemTypeDetail, Unit, ItemCategory, ItemStatus, UsageInstructions, UsageTime, ItemClass, ItemClassDetail, GenericName, Factory, Supplier, FactoryToSupplier, ItemMaster, ItemGroup, PharmacyInfo, ItemPrice, SellingPricePercentage, PatientGroup, PatientGuarantor, InitialStock, DoctorItem, DoctorItemPackage, UserToRoom, RoomToPharmacy, PlanningVerificator, ScheduleSeries, ScheduleException, CardType, PaymentMethod } from 'entity' import { FareType, RoomStock, Administrativu, Aldeia, District, Menu, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift, HospitalInformation, ItemOrigin, ItemType, ItemTypeDetail, Unit, ItemCategory, ItemStatus, UsageInstructions, UsageTime, ItemClass, ItemClassDetail, GenericName, Factory, Supplier, FactoryToSupplier, ItemMaster, ItemGroup, PharmacyInfo, ItemPrice, SellingPricePercentage, PatientGroup, PatientGuarantor, InitialStock, DoctorItem, DoctorItemPackage, UserToRoom, RoomToPharmacy, PlanningVerificator, ScheduleSeries, ScheduleException, CardType, PaymentMethod } from 'entity'
const log: Logger<ILogObj> = new Logger({ name: '[OrmHelper]', type: 'pretty' });
export class OrmHelper { export class OrmHelper {
static DB: DataSource = null static DB: DataSource = null
private static retryDelay = 5000 // 5 detik
private static maxRetries = 10
static setup() { static setup() {
const log: Logger<ILogObj> = new Logger({ name: '[OrmHelper]', type: 'pretty' });
const engine: 'mysql' | 'postgres' = config.get("database.engine") const engine: 'mysql' | 'postgres' = config.get("database.engine")
OrmHelper.DB = new DataSource({ OrmHelper.DB = new DataSource({
@ -90,65 +20,48 @@ export class OrmHelper {
database: String(config.get("database.database")), database: String(config.get("database.database")),
synchronize: true, synchronize: true,
logging: config.get('database.logging'), logging: config.get('database.logging'),
// Tambahan config pool
extra: {
max: 20,
min: 2,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
},
entities: [Menu, Administrativu, Aldeia, District, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift, HospitalInformation, ItemGroup, entities: [Menu, Administrativu, Aldeia, District, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift, HospitalInformation, ItemGroup,
ItemOrigin, ItemType, ItemTypeDetail, Unit, ItemCategory, ItemStatus, UsageInstructions, UsageTime, ItemClass, ItemClassDetail, GenericName, Factory, Supplier, FactoryToSupplier, ItemMaster, PharmacyInfo, ItemPrice, SellingPricePercentage, PatientGroup, PatientGuarantor, InitialStock, DoctorItem, DoctorItemPackage, UserToRoom, RoomToPharmacy, PlanningVerificator, RoomStock, ScheduleSeries, ScheduleException, FareType, CardType, PaymentMethod ItemOrigin,
ItemType,
ItemTypeDetail,
Unit,
ItemCategory,
ItemStatus,
UsageInstructions,
UsageTime,
ItemClass,
ItemClassDetail,
GenericName,
Factory,
Supplier,
FactoryToSupplier,
ItemMaster,
PharmacyInfo,
ItemPrice,
SellingPricePercentage,
PatientGroup,
PatientGuarantor,
InitialStock,
DoctorItem,
DoctorItemPackage,
UserToRoom,
RoomToPharmacy,
PlanningVerificator,
RoomStock,
ScheduleSeries,
ScheduleException,
FareType,
CardType,
PaymentMethod
], ],
subscribers: [], subscribers: [],
migrations: [], migrations: [],
}) })
OrmHelper.initialize() OrmHelper.DB.initialize()
} .then(() => {
// here you can start to work with your database
static async initialize(retryCount = 0) { })
try { .catch((error: any) => log.error(error))
// Kalau sebelumnya sudah connect, destroy dulu
if (OrmHelper.DB.isInitialized) {
await OrmHelper.DB.destroy()
}
await OrmHelper.DB.initialize()
log.info("Database connected successfully")
// Monitor koneksi — reconnect kalau terputus
OrmHelper.monitorConnection()
} catch (error: any) {
log.error(`Database connection failed (attempt ${retryCount + 1}):`, error.message)
if (retryCount < OrmHelper.maxRetries) {
log.info(`Retrying in ${OrmHelper.retryDelay / 1000}s...`)
setTimeout(() => OrmHelper.initialize(retryCount + 1), OrmHelper.retryDelay)
} else {
log.error("Max retries reached. Could not connect to database.")
}
}
}
static monitorConnection() {
// Cek koneksi setiap 30 detik
setInterval(async () => {
try {
if (!OrmHelper.DB.isInitialized) {
log.warn("Database connection lost, reconnecting...")
await OrmHelper.initialize()
return
}
// Ping DB untuk validasi koneksi masih hidup
await OrmHelper.DB.query("SELECT 1")
} catch (error: any) {
log.warn("Database ping failed, reconnecting...", error.message)
await OrmHelper.initialize()
}
}, 30000) // setiap 30 detik
} }
} }