Skip to content

Commit

Permalink
perf(theme): start on demand, fixed view engine
Browse files Browse the repository at this point in the history
  • Loading branch information
wibus-wee committed Aug 13, 2022
1 parent e93b102 commit ec9e49d
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 28 deletions.
23 changes: 11 additions & 12 deletions src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { MyLogger } from "./processors/logger/logger.service";
import { isDev } from "./utils/environment.utils";
import { argv } from "zx-cjs";
import { join } from "path";
import { THEME_DIR } from "./constants/path.constant";
import { ConfigsService } from "./modules/configs/configs.service";
import { PUBLIC_DIR, THEME_DIR } from "./constants/path.constant";
import { ThemeService } from "./modules/theme/theme.service";

// const APIVersion = 1
const Origin = CROSS_DOMAIN.allowedOrigins;
Expand All @@ -24,22 +24,19 @@ export async function bootstrap() {
{ logger: ["error", "debug"] }
);

const configService = app.get(ConfigsService);
const theme = configService.model.findOne({ name: "theme" });
const themeEnabled = theme?.value?.find((item) => item.enabled);
if (themeEnabled) {
const themeService = app.get(ThemeService);
const themeEnabled = await themeService.currentTheme();
if (!argv.noTheme) {
app.useStaticAssets({
root: join(THEME_DIR, themeEnabled?.name || "default", "public"),
root: join(PUBLIC_DIR),
prefix: "/public/",
});
app.setViewEngine({
engine: {
handlebars: require("handlebars"),
"art-template": require("art-template"),
ejs: require("ejs"),
},
templates: join(THEME_DIR, themeEnabled.name || "default"),
viewExt: themeEnabled.viewExt || "art-template",
templates: join(THEME_DIR), // 模板目录,模板名字应在 Render 中指定
viewExt: "ejs",
defaultContext: {
dev: process.env.NODE_ENV === "development",
},
Expand Down Expand Up @@ -102,7 +99,9 @@ export async function bootstrap() {
consola.debug(`[${prefix + pid}] OpenApi: ${url}/api-docs`);
}
consola.success(`[${prefix + pid}] 服务器正在监听: ${url}`);

if (themeEnabled) {
consola.success(`[${prefix + pid}] 当前主题: ${themeEnabled.name}`);
}
Logger.log(
`NxServer 已启动. ${chalk.yellow(`+${performance.now() | 0}ms`)}`
);
Expand Down
1 change: 1 addition & 0 deletions src/constants/path.constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export const PLUGIN_DIR = join(DATA_DIR, "plugins");
export const LOG_DIR = join(DATA_DIR, "log");
export const BACKUP_DIR = join(DATA_DIR, "backup");
export const THEME_DIR = join(DATA_DIR, "themes");
export const PUBLIC_DIR = join(DATA_DIR, "public");
5 changes: 4 additions & 1 deletion src/global/index.global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Logger } from "@nestjs/common";
import { chalk, $ } from "zx-cjs";
import { mkdirSync } from "fs";
import "zx-cjs/globals";
import { DATA_DIR, LOG_DIR, PLUGIN_DIR, THEME_DIR } from "~/constants/path.constant";
import { DATA_DIR, LOG_DIR, PLUGIN_DIR, PUBLIC_DIR, THEME_DIR } from "~/constants/path.constant";
import { consola, registerStdLogger } from "./consola.global";
import "./dayjs.global";
import { isDev } from "./env.global";
Expand All @@ -21,6 +21,9 @@ function mkdirs() {

mkdirSync(THEME_DIR, { recursive: true });
Logger.log(chalk.blue(`主题文件夹 已准备好: ${THEME_DIR}`));

mkdirSync(PUBLIC_DIR, { recursive: true });
Logger.log(chalk.blue(`公共文件夹 已准备好: ${PUBLIC_DIR}`));
}

function registerGlobal() {
Expand Down
8 changes: 1 addition & 7 deletions src/modules/configs/configs.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @author: Wibus
* @Date: 2022-06-22 07:54:11
* @LastEditors: Wibus
* @LastEditTime: 2022-08-12 21:10:21
* @LastEditTime: 2022-08-13 11:11:45
* Coding With IU
*/

Expand Down Expand Up @@ -141,12 +141,6 @@ export class ThemeDto {
@JSONSchemaPlainField("主题名称")
name: string;

@IsNotEmpty({ message: "主题使用的引擎不能为空" })
@IsString({ message: "主题使用的引擎必须是字符串" })
@JSONSchemaPlainField("主题使用的引擎")
viewExt: "ejs" | "handlebars" | "art-template";


@IsOptional()
@JSONSchemaPlainField("主题配置")
configs: any;
Expand Down
31 changes: 29 additions & 2 deletions src/modules/theme/theme.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,31 @@
import { Controller } from '@nestjs/common';
import { Controller, Get, Query } from '@nestjs/common';
import { ApiName } from '~/common/decorator/openapi.decorator';
import { ThemeService } from './theme.service';

@Controller('theme')
export class ThemeController {}
@ApiName
export class ThemeController {
constructor(
private readonly themeService: ThemeService,
) {}

@Get('/admin/available')
async availableThemes() {
return this.themeService.availableThemes();
}

@Get('/admin/up')
async turnOnTheme(@Query('name') name: string) {
return this.themeService.turnOnTheme(name);
}

@Get('/admin/current')
async currentTheme() {
return this.themeService.currentTheme();
}

@Get('/admin/off')
async turnOffTheme(@Query('name') name: string) {
return this.themeService.turnOffTheme(name);
}
}
41 changes: 35 additions & 6 deletions src/modules/theme/theme.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { BadRequestException, Get, Injectable, Logger, Render } from '@nestjs/common';
import { YAML } from 'zx-cjs';
import { THEME_DIR } from '~/constants/path.constant';
import { ThemeDto } from '../configs/configs.dto';
Expand All @@ -7,16 +7,14 @@ import { ConfigsService } from '../configs/configs.service';
@Injectable()
export class ThemeService {
private logger: Logger;
private CORE_VERSION = require('../../../package.json').version
constructor(
private readonly configsService: ConfigsService,

) {
this.logger = new Logger(ThemeService.name)
}


CORE_VERSION = require('../../../package.json').version

private async turnOnThemeLibs(name: string) {
// 查找配置文件是否存在
const themeConfigFile = await fs
Expand All @@ -38,7 +36,7 @@ export class ThemeService {
) {
// 提醒建议使用的版本
this.CORE_VERSION !== themeConfig.recommend_version && this.logger.warn(`主题 ${name} 建议使用版本 ${themeConfig.recommend_version}`)
} else {
} else if ( themeConfig.support_max_version == 'latest' ) {} else {
throw new BadRequestException(`主题 ${name} 不支持当前版本`);
}

Expand All @@ -47,6 +45,14 @@ export class ThemeService {
}
}

/**
* 可用的主题列表
*/
async availableThemes() {
const themes = await fs.readdir(THEME_DIR); // 获取主题目录下的所有主题
return themes.filter(theme => fs.existsSync(path.join(THEME_DIR, theme, 'theme.yaml')));
}

/**
* turnOnTheme 启动主题
*/
Expand All @@ -58,10 +64,33 @@ export class ThemeService {
name,
enable: true,
configs: themeConfig.configs ? themeConfig.configs : {},
viewExt: themeConfig.viewExt || 'art-template',
}
await this.configsService.patch('theme', theme); // 更新主题配置
return `主题 ${name} 启动成功`;
}
}

async turnOffTheme(name: string) {
if (fs.existsSync(path.join(THEME_DIR, name))) { // 检查主题是否存在
const theme: ThemeDto = { // 创建主题对象
name,
enable: false,
configs: {},
}
await this.configsService.patch('theme', theme); // 更新主题配置
return `主题 ${name} 关闭成功`;
}
}

async currentTheme() {
const theme = await this.configsService.get('theme');
return theme;
}

// ********************************************************
// 以下是主题渲染相关的方法

@Get('/')

async renderIndex() {}
}

0 comments on commit ec9e49d

Please sign in to comment.