feat: 安装向导页支持滚动并新增 MySQL/Redis 连接测试

Install 页作为独立满屏路由自身承载纵向滚动,修复内容超出视口无法滚动;
MySQL/Redis 卡片新增测试连接按钮,后端新增 /api/install/test-connection(仅安装模式可用,
不建库不落盘;MySQL 库不存在也视为可连接因安装时会自动建库)。
This commit is contained in:
Nixevol
2026-07-09 15:04:45 +08:00
parent 0780fc2d0f
commit 8db618a807
6 changed files with 182 additions and 5 deletions
+3
View File
@@ -212,6 +212,9 @@
"failed": "Installation failed",
"done": "Initialized. The service is restarting, please wait…",
"loadFailed": "Failed to read installation status",
"testConnection": "Test",
"testOk": "Connected",
"testFailed": "Connection failed",
"defaultAppName": "Artwork Traceability Platform",
"defaultAdminName": "Administrator"
},
+3
View File
@@ -212,6 +212,9 @@
"failed": "安装失败",
"done": "初始化完成,服务正在重启,请稍候…",
"loadFailed": "读取安装状态失败",
"testConnection": "测试连接",
"testOk": "连接成功",
"testFailed": "连接失败",
"defaultAppName": "艺术品溯源平台",
"defaultAdminName": "管理员"
},
+83 -3
View File
@@ -34,7 +34,10 @@
</section>
<section class="box">
<h2>MySQL</h2>
<div class="box-head">
<h2>MySQL</h2>
<n-button size="tiny" :loading="testingMysql" @click="testMysql">{{ tt('testConnection') }}</n-button>
</div>
<label><span>{{ tt('host') }}</span><n-input v-model:value="form.mysql.host" /></label>
<label><span>{{ tt('port') }}</span><n-input-number v-model:value="form.mysql.port" :min="1" :show-button="false" class="full" /></label>
<label><span>{{ tt('database') }}</span><n-input v-model:value="form.mysql.database" /></label>
@@ -42,14 +45,19 @@
<label><span>{{ tt('password') }}</span><n-input v-model:value="form.mysql.password" type="password" show-password-on="click" /></label>
<label><span>{{ tt('adminUser') }}</span><n-input v-model:value="form.mysql.adminUsername" /></label>
<label><span>{{ tt('adminPass') }}</span><n-input v-model:value="form.mysql.adminPassword" type="password" show-password-on="click" /></label>
<p v-if="mysqlTest" class="test-result" :class="mysqlTest.ok ? 'ok' : 'fail'">{{ mysqlTest.msg }}</p>
<p class="hint">{{ tt('mysqlAdminHint') }}</p>
</section>
<section class="box">
<h2>Redis</h2>
<div class="box-head">
<h2>Redis</h2>
<n-button size="tiny" :loading="testingRedis" @click="testRedis">{{ tt('testConnection') }}</n-button>
</div>
<label><span>{{ tt('host') }}</span><n-input v-model:value="form.redis.host" /></label>
<label><span>{{ tt('port') }}</span><n-input-number v-model:value="form.redis.port" :min="1" :show-button="false" class="full" /></label>
<label><span>{{ tt('password') }}</span><n-input v-model:value="form.redis.password" type="password" show-password-on="click" /></label>
<p v-if="redisTest" class="test-result" :class="redisTest.ok ? 'ok' : 'fail'">{{ redisTest.msg }}</p>
</section>
<section class="box">
@@ -159,11 +167,56 @@ const submitting = ref(false);
const installed = ref(false);
const error = ref('');
const success = ref('');
const testingMysql = ref(false);
const testingRedis = ref(false);
const mysqlTest = ref<{ ok: boolean; msg: string } | null>(null);
const redisTest = ref<{ ok: boolean; msg: string } | null>(null);
function goAdmin(): void {
location.href = '/admin';
}
async function testConnection(payload: Record<string, unknown>): Promise<{ ok: boolean; msg: string }> {
try {
const res = await fetch('/api/install/test-connection', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const body = await res.json();
if (!res.ok || body.code !== 0) throw new Error(body.message || tt('testFailed'));
return { ok: true, msg: body.data?.message || tt('testOk') };
} catch (e) {
return { ok: false, msg: (e as Error).message || tt('testFailed') };
}
}
async function testMysql(): Promise<void> {
testingMysql.value = true;
mysqlTest.value = null;
mysqlTest.value = await testConnection({
target: 'mysql',
host: form.mysql.host,
port: form.mysql.port,
database: form.mysql.database,
username: form.mysql.username,
password: form.mysql.password,
});
testingMysql.value = false;
}
async function testRedis(): Promise<void> {
testingRedis.value = true;
redisTest.value = null;
redisTest.value = await testConnection({
target: 'redis',
host: form.redis.host,
port: form.redis.port,
password: form.redis.password,
});
testingRedis.value = false;
}
onMounted(async () => {
try {
const res = await fetch('/api/install/status');
@@ -224,7 +277,9 @@ async function submit(): Promise<void> {
<style scoped>
.install-page {
min-height: 100vh;
/* 全局 #app 为 overflow-y:hidden,安装页是独立满屏路由,需自身承载纵向滚动 */
height: 100vh;
overflow-y: auto;
padding: 24px;
display: flex;
justify-content: center;
@@ -273,6 +328,31 @@ async function submit(): Promise<void> {
padding-bottom: 8px;
border-bottom: 1px solid var(--border, #e9edf4);
}
.box-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border, #e9edf4);
}
.box-head h2 {
margin: 0;
padding: 0;
border: 0;
}
.test-result {
margin: 2px 0 0;
font-size: 12px;
line-height: 1.5;
word-break: break-all;
}
.test-result.ok {
color: #18a058;
}
.test-result.fail {
color: #d03050;
}
.box label {
display: grid;
grid-template-columns: 132px 1fr;
+32
View File
@@ -119,6 +119,38 @@ export class InstallStorageDto {
ossAccessKeySecret?: string;
}
export class TestConnectionDto {
@ApiProperty({ enum: ['mysql', 'redis'] })
@IsIn(['mysql', 'redis'])
target!: 'mysql' | 'redis';
@ApiProperty()
@IsString()
@IsNotEmpty()
host!: string;
@ApiProperty()
@Type(() => Number)
@IsInt()
@Min(1)
port!: number;
@ApiPropertyOptional()
@IsOptional()
@IsString()
database?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
username?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
password?: string;
}
export class InstallRequestDto {
@ApiProperty()
@IsString()
+8 -1
View File
@@ -1,7 +1,7 @@
import { Body, Controller, Get, Post } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Public } from '../common/decorators/public.decorator';
import { InstallRequestDto } from './dto/install.dto';
import { InstallRequestDto, TestConnectionDto } from './dto/install.dto';
import { InstallService } from './install.service';
@ApiTags('Install')
@@ -16,6 +16,13 @@ export class InstallController {
return this.installService.status();
}
@Public()
@Post('test-connection')
@ApiOperation({ summary: 'Test MySQL/Redis connectivity' })
testConnection(@Body() dto: TestConnectionDto) {
return this.installService.testConnection(dto);
}
@Public()
@Post()
@ApiOperation({ summary: 'Initialize installation' })
+53 -1
View File
@@ -7,7 +7,7 @@ import * as bcrypt from 'bcryptjs';
import { PrismaClient, RoleType, UserStatus } from '@prisma/client';
import Redis from 'ioredis';
import { envFilePath, isInstallMode } from '../config/runtime-config';
import { InstallRequestDto } from './dto/install.dto';
import { InstallRequestDto, TestConnectionDto } from './dto/install.dto';
const ENCRYPTED_PREFIX = 'enc:v1:';
@@ -48,6 +48,58 @@ export class InstallService {
return { installed: true, restartRequired: true };
}
// 安装页「测试连接」:只连通、不建库、不落盘。target=mysql|redis
async testConnection(dto: TestConnectionDto): Promise<{ success: true; message: string }> {
// 仅安装模式可用,避免安装完成后被当作公开的内网端口探测工具
if (!isInstallMode()) {
throw new Error('系统已安装,连接测试不可用');
}
if (dto.target === 'redis') {
const redis = new Redis({
host: dto.host,
port: dto.port,
password: dto.password || undefined,
maxRetriesPerRequest: 1,
connectTimeout: 5000,
lazyConnect: true,
});
try {
await redis.connect();
await redis.ping();
} finally {
redis.disconnect();
}
return { success: true, message: 'Redis 连接成功' };
}
// MySQL:优先连业务库,库不存在(P1049)也视为「可连接」,因为安装时会自动建库
const user = encodeURIComponent(dto.username ?? '');
const password = encodeURIComponent(dto.password ?? '');
const base = `mysql://${user}:${password}@${dto.host}:${dto.port}`;
const dbName = dto.database || '';
const tryConnect = async (url: string) => {
const prisma = new PrismaClient({ datasources: { db: { url } } });
try {
await prisma.$connect();
await prisma.$queryRaw`SELECT 1`;
} finally {
await prisma.$disconnect().catch(() => undefined);
}
};
try {
await tryConnect(`${base}/${encodeURIComponent(dbName)}`);
return { success: true, message: 'MySQL 连接成功,业务库已存在' };
} catch (e) {
const code = (e as { code?: string }).code;
const msg = (e as Error).message || '';
if (code === 'P1003' || /Unknown database|P1049|does not exist/i.test(msg)) {
// 库不存在,但服务器可连接:再连 information_schema 确认凭据可用
await tryConnect(`${base}/information_schema`);
return { success: true, message: 'MySQL 连接成功,业务库不存在(安装时将自动创建)' };
}
throw new Error(`MySQL 连接失败:${msg}`);
}
}
private buildMysqlUrl(dto: InstallRequestDto): string {
const user = encodeURIComponent(dto.mysql.username);
const password = encodeURIComponent(dto.mysql.password);