Files
certd/packages/ui/certd-server/src/modules/auto/auto-init-site.ts
T

83 lines
2.5 KiB
TypeScript
Raw Normal View History

import { Autoload, Config, Init, Inject, Scope, ScopeEnum } from '@midwayjs/core';
2024-10-03 22:03:49 +08:00
import { logger } from '@certd/pipeline';
import { UserService } from '../sys/authority/service/user-service.js';
2024-10-04 00:52:19 +08:00
import { PlusService, SysSettingsService } from '@certd/lib-server';
2024-07-15 00:30:33 +08:00
import { nanoid } from 'nanoid';
2024-10-03 22:03:49 +08:00
import { SysInstallInfo, SysPrivateSettings } from '@certd/lib-server';
2024-08-27 13:46:19 +08:00
import crypto from 'crypto';
2024-09-24 11:11:08 +08:00
2024-07-15 00:30:33 +08:00
export type InstallInfo = {
installTime: number;
instanceId?: string;
};
@Autoload()
@Scope(ScopeEnum.Singleton)
export class AutoInitSite {
@Inject()
userService: UserService;
@Config('typeorm.dataSource.default.type')
dbType: string;
2024-07-15 00:30:33 +08:00
@Inject()
sysSettingsService: SysSettingsService;
2024-09-24 11:11:08 +08:00
@Inject()
plusService: PlusService;
2024-07-15 00:30:33 +08:00
@Init()
async init() {
logger.info('初始化站点开始');
2024-08-29 10:09:22 +08:00
await this.startOptimizeDb();
2024-08-27 13:46:19 +08:00
//安装信息
2024-07-15 00:30:33 +08:00
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
if (!installInfo.siteId) {
installInfo.siteId = nanoid();
await this.sysSettingsService.saveSetting(installInfo);
}
if (!installInfo.siteId) {
installInfo.siteId = nanoid();
await this.sysSettingsService.saveSetting(installInfo);
}
2024-08-27 13:46:19 +08:00
//private信息
const privateInfo = await this.sysSettingsService.getSetting<SysPrivateSettings>(SysPrivateSettings);
if (!privateInfo.jwtKey) {
privateInfo.jwtKey = nanoid();
await this.sysSettingsService.saveSetting(privateInfo);
}
if (!privateInfo.encryptSecret) {
const secretKey = crypto.randomBytes(32);
privateInfo.encryptSecret = secretKey.toString('base64');
await this.sysSettingsService.saveSetting(privateInfo);
}
2024-08-02 22:58:29 +08:00
// 授权许可
2024-09-24 11:11:08 +08:00
await this.plusService.verify();
2024-08-02 22:58:29 +08:00
2024-07-15 00:30:33 +08:00
logger.info('初始化站点完成');
}
2024-08-29 10:09:22 +08:00
async startOptimizeDb() {
//优化数据库
//检查当前数据库类型为sqlite
if (this.dbType === 'better-sqlite3') {
2024-08-29 10:09:22 +08:00
const res = await this.userService.repository.query('PRAGMA auto_vacuum;');
if (!(res && res.length > 0 && res[0].auto_vacuum > 0)) {
//未开启自动优化
await this.userService.repository.query('PRAGMA auto_vacuum = INCREMENTAL;');
logger.info('sqlite数据库自动优化已开启');
}
const optimizeDb = async () => {
logger.info('sqlite数据库空间优化开始');
await this.userService.repository.query('VACUUM');
logger.info('sqlite数据库空间优化完成');
};
2024-08-29 10:09:22 +08:00
await optimizeDb();
setInterval(optimizeDb, 1000 * 60 * 60 * 24);
}
}
2024-07-15 00:30:33 +08:00
}