feat: set cached config when import, refactor db

This commit is contained in:
shinya
2025-08-15 18:47:51 +08:00
parent f8c7289d54
commit 8b34f3e403
10 changed files with 56 additions and 98 deletions
+2 -5
View File
@@ -4,7 +4,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth'; import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { getStorage } from '@/lib/db'; import { db } from '@/lib/db';
import { IStorage } from '@/lib/types'; import { IStorage } from '@/lib/types';
export const runtime = 'edge'; export const runtime = 'edge';
@@ -45,7 +45,6 @@ export async function POST(request: NextRequest) {
// 获取配置与存储 // 获取配置与存储
const adminConfig = await getConfig(); const adminConfig = await getConfig();
const storage: IStorage | null = getStorage();
// 权限与身份校验 // 权限与身份校验
if (username !== process.env.USERNAME) { if (username !== process.env.USERNAME) {
@@ -176,9 +175,7 @@ export async function POST(request: NextRequest) {
} }
// 持久化到存储 // 持久化到存储
if (storage && typeof (storage as any).setAdminConfig === 'function') { await db.saveAdminConfig(adminConfig);
await (storage as any).setAdminConfig(adminConfig);
}
return NextResponse.json( return NextResponse.json(
{ ok: true }, { ok: true },
+6 -15
View File
@@ -4,7 +4,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth'; import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig, refineConfig } from '@/lib/config'; import { getConfig, refineConfig } from '@/lib/config';
import { getStorage } from '@/lib/db'; import { db } from '@/lib/db';
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage'; const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
@@ -26,7 +26,6 @@ export async function POST(request: NextRequest) {
try { try {
// 检查用户权限 // 检查用户权限
let adminConfig = await getConfig(); let adminConfig = await getConfig();
const storage = getStorage();
// 仅站长可以修改配置文件 // 仅站长可以修改配置文件
if (username !== process.env.USERNAME) { if (username !== process.env.USERNAME) {
@@ -77,19 +76,11 @@ export async function POST(request: NextRequest) {
adminConfig = refineConfig(adminConfig); adminConfig = refineConfig(adminConfig);
// 更新配置文件 // 更新配置文件
if (storage && typeof (storage as any).setAdminConfig === 'function') { await db.saveAdminConfig(adminConfig);
await (storage as any).setAdminConfig(adminConfig); return NextResponse.json({
success: true,
return NextResponse.json({ message: '配置文件更新成功',
success: true, });
message: '配置文件更新成功',
});
} else {
return NextResponse.json(
{ error: '存储服务不可用' },
{ status: 500 }
);
}
} catch (error) { } catch (error) {
console.error('更新配置文件失败:', error); console.error('更新配置文件失败:', error);
return NextResponse.json( return NextResponse.json(
@@ -7,6 +7,7 @@ import { gunzip } from 'zlib';
import { getAuthInfoFromCookie } from '@/lib/auth'; import { getAuthInfoFromCookie } from '@/lib/auth';
import { SimpleCrypto } from '@/lib/crypto'; import { SimpleCrypto } from '@/lib/crypto';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { setCachedConfig } from '@/lib/config';
const gunzipAsync = promisify(gunzip); const gunzipAsync = promisify(gunzip);
@@ -79,6 +80,7 @@ export async function POST(req: NextRequest) {
// 导入管理员配置 // 导入管理员配置
await db.saveAdminConfig(importData.data.adminConfig); await db.saveAdminConfig(importData.data.adminConfig);
await setCachedConfig(importData.data.adminConfig);
// 导入用户数据 // 导入用户数据
const userData = importData.data.userData; const userData = importData.data.userData;
+2 -5
View File
@@ -4,7 +4,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth'; import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { getStorage } from '@/lib/db'; import { db } from '@/lib/db';
export const runtime = 'edge'; export const runtime = 'edge';
@@ -66,7 +66,6 @@ export async function POST(request: NextRequest) {
} }
const adminConfig = await getConfig(); const adminConfig = await getConfig();
const storage = getStorage();
// 权限校验 // 权限校验
if (username !== process.env.USERNAME) { if (username !== process.env.USERNAME) {
@@ -93,9 +92,7 @@ export async function POST(request: NextRequest) {
}; };
// 写入数据库 // 写入数据库
if (storage && typeof (storage as any).setAdminConfig === 'function') { await db.saveAdminConfig(adminConfig);
await (storage as any).setAdminConfig(adminConfig);
}
return NextResponse.json( return NextResponse.json(
{ ok: true }, { ok: true },
+2 -5
View File
@@ -4,7 +4,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth'; import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { getStorage } from '@/lib/db'; import { db } from '@/lib/db';
import { IStorage } from '@/lib/types'; import { IStorage } from '@/lib/types';
export const runtime = 'edge'; export const runtime = 'edge';
@@ -45,7 +45,6 @@ export async function POST(request: NextRequest) {
// 获取配置与存储 // 获取配置与存储
const adminConfig = await getConfig(); const adminConfig = await getConfig();
const storage: IStorage | null = getStorage();
// 权限与身份校验 // 权限与身份校验
if (username !== process.env.USERNAME) { if (username !== process.env.USERNAME) {
@@ -144,9 +143,7 @@ export async function POST(request: NextRequest) {
} }
// 持久化到存储 // 持久化到存储
if (storage && typeof (storage as any).setAdminConfig === 'function') { await db.saveAdminConfig(adminConfig);
await (storage as any).setAdminConfig(adminConfig);
}
return NextResponse.json( return NextResponse.json(
{ ok: true }, { ok: true },
+6 -30
View File
@@ -4,8 +4,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth'; import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { getStorage } from '@/lib/db'; import { db } from '@/lib/db';
import { IStorage } from '@/lib/types';
export const runtime = 'edge'; export const runtime = 'edge';
@@ -75,7 +74,6 @@ export async function POST(request: NextRequest) {
// 获取配置与存储 // 获取配置与存储
const adminConfig = await getConfig(); const adminConfig = await getConfig();
const storage: IStorage | null = getStorage();
// 判定操作者角色 // 判定操作者角色
let operatorRole: 'owner' | 'admin'; let operatorRole: 'owner' | 'admin';
@@ -125,13 +123,7 @@ export async function POST(request: NextRequest) {
{ status: 400 } { status: 400 }
); );
} }
if (!storage || typeof storage.registerUser !== 'function') { await db.registerUser(targetUsername!, targetPassword);
return NextResponse.json(
{ error: '存储未配置用户注册' },
{ status: 500 }
);
}
await storage.registerUser(targetUsername!, targetPassword);
// 更新配置 // 更新配置
adminConfig.UserConfig.Users.push({ adminConfig.UserConfig.Users.push({
username: targetUsername!, username: targetUsername!,
@@ -139,7 +131,7 @@ export async function POST(request: NextRequest) {
}); });
targetEntry = targetEntry =
adminConfig.UserConfig.Users[ adminConfig.UserConfig.Users[
adminConfig.UserConfig.Users.length - 1 adminConfig.UserConfig.Users.length - 1
]; ];
break; break;
} }
@@ -254,14 +246,7 @@ export async function POST(request: NextRequest) {
); );
} }
if (!storage || typeof storage.changePassword !== 'function') { await db.changePassword(targetUsername!, targetPassword);
return NextResponse.json(
{ error: '存储未配置密码修改功能' },
{ status: 500 }
);
}
await storage.changePassword(targetUsername!, targetPassword);
break; break;
} }
case 'deleteUser': { case 'deleteUser': {
@@ -287,14 +272,7 @@ export async function POST(request: NextRequest) {
); );
} }
if (!storage || typeof storage.deleteUser !== 'function') { await db.deleteUser(targetUsername!);
return NextResponse.json(
{ error: '存储未配置用户删除功能' },
{ status: 500 }
);
}
await storage.deleteUser(targetUsername!);
// 从配置中移除用户 // 从配置中移除用户
const userIndex = adminConfig.UserConfig.Users.findIndex( const userIndex = adminConfig.UserConfig.Users.findIndex(
@@ -312,9 +290,7 @@ export async function POST(request: NextRequest) {
} }
// 将更新后的配置写入数据库 // 将更新后的配置写入数据库
if (storage && typeof (storage as any).setAdminConfig === 'function') { await db.saveAdminConfig(adminConfig);
await (storage as any).setAdminConfig(adminConfig);
}
return NextResponse.json( return NextResponse.json(
{ ok: true }, { ok: true },
+2 -11
View File
@@ -3,7 +3,7 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth'; import { getAuthInfoFromCookie } from '@/lib/auth';
import { getStorage } from '@/lib/db'; import { db } from '@/lib/db';
import { IStorage } from '@/lib/types'; import { IStorage } from '@/lib/types';
export const runtime = 'edge'; export const runtime = 'edge';
@@ -46,17 +46,8 @@ export async function POST(request: NextRequest) {
); );
} }
// 获取存储实例
const storage: IStorage | null = getStorage();
if (!storage || typeof storage.changePassword !== 'function') {
return NextResponse.json(
{ error: '存储服务不支持修改密码' },
{ status: 500 }
);
}
// 修改密码 // 修改密码
await storage.changePassword(username, newPassword); await db.changePassword(username, newPassword);
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
} catch (error) { } catch (error) {
+2 -5
View File
@@ -3,7 +3,7 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { getConfig, refineConfig } from '@/lib/config'; import { getConfig, refineConfig } from '@/lib/config';
import { db, getStorage } from '@/lib/db'; import { db } from '@/lib/db';
import { fetchVideoDetail } from '@/lib/fetchVideoDetail'; import { fetchVideoDetail } from '@/lib/fetchVideoDetail';
import { SearchResult } from '@/lib/types'; import { SearchResult } from '@/lib/types';
@@ -72,10 +72,7 @@ async function refreshConfig() {
config.ConfigFile = decodedContent; config.ConfigFile = decodedContent;
config.ConfigSubscribtion.LastCheck = new Date().toISOString(); config.ConfigSubscribtion.LastCheck = new Date().toISOString();
config = refineConfig(config); config = refineConfig(config);
const storage = getStorage(); await db.saveAdminConfig(config);
if (storage && typeof (storage as any).setAdminConfig === 'function') {
await (storage as any).setAdminConfig(config);
}
} catch (e) { } catch (e) {
console.error('刷新配置失败:', e); console.error('刷新配置失败:', e);
} }
+23 -21
View File
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any, no-console, @typescript-eslint/no-non-null-assertion */ /* eslint-disable @typescript-eslint/no-explicit-any, no-console, @typescript-eslint/no-non-null-assertion */
import { getStorage } from '@/lib/db'; import { db } from '@/lib/db';
import { AdminConfig } from './admin.types'; import { AdminConfig } from './admin.types';
@@ -178,14 +178,11 @@ async function getInitConfig(configFile: string, subConfig: {
}; };
// 补充用户信息 // 补充用户信息
const storage = getStorage();
let userNames: string[] = []; let userNames: string[] = [];
if (storage && typeof (storage as any).getAllUsers === 'function') { try {
try { userNames = await db.getAllUsers();
userNames = await (storage as any).getAllUsers(); } catch (e) {
} catch (e) { console.error('获取用户列表失败:', e);
console.error('获取用户列表失败:', e);
}
} }
const allUsers = userNames.filter((u) => u !== process.env.USERNAME).map((u) => ({ const allUsers = userNames.filter((u) => u !== process.env.USERNAME).map((u) => ({
username: u, username: u,
@@ -232,10 +229,11 @@ export async function getConfig(): Promise<AdminConfig> {
} }
// 读 db // 读 db
const storage = getStorage();
let adminConfig: AdminConfig | null = null; let adminConfig: AdminConfig | null = null;
if (storage && typeof (storage as any).getAdminConfig === 'function') { try {
adminConfig = await (storage as any).getAdminConfig(); adminConfig = await db.getAdminConfig();
} catch (e) {
console.error('获取管理员配置失败:', e);
} }
// db 中无配置,执行一次初始化 // db 中无配置,执行一次初始化
@@ -247,20 +245,20 @@ export async function getConfig(): Promise<AdminConfig> {
} }
export async function resetConfig() { export async function resetConfig() {
let originConfig: AdminConfig; let originConfig: AdminConfig | null = null;
const storage = getStorage(); try {
if (storage && typeof (storage as any).getAdminConfig === 'function') { originConfig = await db.getAdminConfig();
originConfig = await (storage as any).getAdminConfig(); } catch (e) {
} else { console.error('获取管理员配置失败:', e);
}
if (!originConfig) {
originConfig = {} as AdminConfig; originConfig = {} as AdminConfig;
} }
const adminConfig = await getInitConfig(originConfig.ConfigFile, originConfig.ConfigSubscribtion); const adminConfig = await getInitConfig(originConfig.ConfigFile, originConfig.ConfigSubscribtion);
cachedConfig = adminConfig; cachedConfig = adminConfig;
if (storage && typeof (storage as any).setAdminConfig === 'function') { await db.saveAdminConfig(adminConfig);
await (storage as any).setAdminConfig(adminConfig);
}
return; return;
} }
export async function getCacheTime(): Promise<number> { export async function getCacheTime(): Promise<number> {
@@ -277,3 +275,7 @@ export async function getAvailableApiSites(): Promise<ApiSite[]> {
detail: s.detail, detail: s.detail,
})); }));
} }
export async function setCachedConfig(config: AdminConfig) {
cachedConfig = config;
}
+9 -1
View File
@@ -29,7 +29,7 @@ function createStorage(): IStorage {
// 单例存储实例 // 单例存储实例
let storageInstance: IStorage | null = null; let storageInstance: IStorage | null = null;
export function getStorage(): IStorage { function getStorage(): IStorage {
if (!storageInstance) { if (!storageInstance) {
storageInstance = createStorage(); storageInstance = createStorage();
} }
@@ -142,6 +142,14 @@ export class DbManager {
return this.storage.checkUserExist(userName); return this.storage.checkUserExist(userName);
} }
async changePassword(userName: string, newPassword: string): Promise<void> {
await this.storage.changePassword(userName, newPassword);
}
async deleteUser(userName: string): Promise<void> {
await this.storage.deleteUser(userName);
}
// ---------- 搜索历史 ---------- // ---------- 搜索历史 ----------
async getSearchHistory(userName: string): Promise<string[]> { async getSearchHistory(userName: string): Promise<string[]> {
return this.storage.getSearchHistory(userName); return this.storage.getSearchHistory(userName);