初始化项目结构和基础模块

完成内容:
- 创建前后端项目目录结构
- 初始化 Node.js + TypeScript 后端项目 (Fastify)
- 初始化 Vue 3 + TypeScript 前端项目 (Vite)
- 配置 Prisma ORM 和 MySQL 数据库
- 创建数据库 Schema 和种子数据
- 实现后端基础模块 (配置、日志、错误处理、验证)
- 创建基础服务类 (BaseService)
- 配置 Git 仓库和忽略文件

技术栈:
- 后端:Fastify + Prisma + MySQL + Winston
- 前端:Vue 3 + TypeScript + Element Plus + Pinia

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-02-03 12:11:57 +08:00
commit 830a17bf46
53 files changed
+16893

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
# 应用配置
NODE_ENV=development
PORT=3000
# 数据库配置
DATABASE_URL="mysql://root:password@localhost:3306/news_aggregator"
# 其他配置
LOG_LEVEL=info
+5
View File
@@ -0,0 +1,5 @@
node_modules/
dist/
.env
*.log
.DS_Store
+2280
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "tsx watch src/app.ts",
"build": "tsc",
"start": "node dist/app.js",
"prisma:generate": "prisma generate",
"prisma:migrate": "prisma migrate dev",
"prisma:studio": "prisma studio"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"@fastify/cors": "^11.2.0",
"@fastify/static": "^9.0.0",
"@prisma/client": "^5.22.0",
"dotenv": "^17.2.3",
"fastify": "^5.7.4",
"node-cron": "^4.2.1",
"openai": "^6.17.0",
"playwright": "^1.58.1",
"prisma": "^5.22.0",
"winston": "^3.19.0"
},
"devDependencies": {
"@types/node": "^25.2.0",
"@types/node-cron": "^3.0.11",
"nodemon": "^3.1.11",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
}
}
+231
View File
@@ -0,0 +1,231 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
// LLM 配置表
model LlmConfig {
id Int @id @default(autoincrement())
name String @db.VarChar(100)
baseUrl String @map("base_url") @db.VarChar(500)
model String @db.VarChar(100)
apiKey String @map("api_key") @db.VarChar(500)
enabled Boolean @default(true) @db.TinyInt
userId Int? @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
topics Topic[]
@@index([userId, enabled], map: "idx_user_enabled")
@@map("llm_configs")
}
// 数据源表
model Source {
id Int @id @default(autoincrement())
name String @db.VarChar(100)
type String @db.VarChar(50) // api/playwright/rss
config Json
cronExpression String @map("cron_expression") @db.VarChar(100)
enabled Boolean @default(true) @db.TinyInt
lastCollectedAt DateTime? @map("last_collected_at")
userId Int? @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
articles Article[]
topicSources TopicSource[]
collectionLogs CollectionLog[]
@@index([userId, enabled], map: "idx_user_enabled")
@@index([type], map: "idx_type")
@@map("sources")
}
// 推送渠道表
model Channel {
id Int @id @default(autoincrement())
name String @db.VarChar(100)
type String @db.VarChar(50) // email/dingtalk/wechat/slack
config Json
enabled Boolean @default(true) @db.TinyInt
userId Int? @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
topicChannels TopicChannel[]
pushLogs PushLog[]
@@index([userId, enabled], map: "idx_user_enabled")
@@index([type], map: "idx_type")
@@map("channels")
}
// 主题表
model Topic {
id Int @id @default(autoincrement())
name String @db.VarChar(100)
description String? @db.Text
processMode String @map("process_mode") @db.VarChar(50) // aggregate/summary/deep_analysis
llmConfigId Int? @map("llm_config_id")
scheduleConfig Json @map("schedule_config")
enabled Boolean @default(true) @db.TinyInt
userId Int? @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
llmConfig LlmConfig? @relation(fields: [llmConfigId], references: [id])
topicSources TopicSource[]
topicChannels TopicChannel[]
reports Report[]
conversations Conversation[]
@@index([userId, enabled], map: "idx_user_enabled")
@@map("topics")
}
// 主题-数据源关联表
model TopicSource {
id Int @id @default(autoincrement())
topicId Int @map("topic_id")
sourceId Int @map("source_id")
createdAt DateTime @default(now()) @map("created_at")
topic Topic @relation(fields: [topicId], references: [id], onDelete: Cascade)
source Source @relation(fields: [sourceId], references: [id], onDelete: Cascade)
@@unique([topicId, sourceId], map: "uk_topic_source")
@@index([topicId], map: "idx_topic")
@@index([sourceId], map: "idx_source")
@@map("topic_sources")
}
// 主题-推送渠道关联表
model TopicChannel {
id Int @id @default(autoincrement())
topicId Int @map("topic_id")
channelId Int @map("channel_id")
createdAt DateTime @default(now()) @map("created_at")
topic Topic @relation(fields: [topicId], references: [id], onDelete: Cascade)
channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)
@@unique([topicId, channelId], map: "uk_topic_channel")
@@index([topicId], map: "idx_topic")
@@index([channelId], map: "idx_channel")
@@map("topic_channels")
}
// 资讯表
model Article {
id Int @id @default(autoincrement())
sourceId Int @map("source_id")
title String @db.VarChar(500)
content String? @db.Text
summary String? @db.Text
url String? @db.VarChar(1000)
publishedAt DateTime? @map("published_at")
collectedAt DateTime @map("collected_at")
rawData Json? @map("raw_data")
createdAt DateTime @default(now()) @map("created_at")
source Source @relation(fields: [sourceId], references: [id])
conversations Conversation[]
@@index([sourceId], map: "idx_source")
@@index([publishedAt], map: "idx_published")
@@index([collectedAt], map: "idx_collected")
@@index([url(length: 255)], map: "idx_url")
@@map("articles")
}
// 报告表
model Report {
id Int @id @default(autoincrement())
topicId Int @map("topic_id")
title String @db.VarChar(500)
content String @db.LongText
periodStart DateTime @map("period_start")
periodEnd DateTime @map("period_end")
status String @db.VarChar(50) // pending/generating/completed/failed
errorMessage String? @map("error_message") @db.Text
articleCount Int @default(0) @map("article_count")
userId Int? @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
topic Topic @relation(fields: [topicId], references: [id])
pushLogs PushLog[]
conversations Conversation[]
@@index([topicId], map: "idx_topic")
@@index([status], map: "idx_status")
@@index([periodStart, periodEnd], map: "idx_period")
@@index([userId, createdAt], map: "idx_user_created")
@@map("reports")
}
// 采集日志表
model CollectionLog {
id Int @id @default(autoincrement())
sourceId Int @map("source_id")
status String @db.VarChar(50) // success/failed
errorMessage String? @map("error_message") @db.Text
articlesCount Int @default(0) @map("articles_count")
startedAt DateTime @map("started_at")
finishedAt DateTime? @map("finished_at")
durationMs Int? @map("duration_ms")
createdAt DateTime @default(now()) @map("created_at")
source Source @relation(fields: [sourceId], references: [id])
@@index([sourceId], map: "idx_source")
@@index([status], map: "idx_status")
@@index([startedAt], map: "idx_started")
@@map("collection_logs")
}
// 推送日志表
model PushLog {
id Int @id @default(autoincrement())
reportId Int @map("report_id")
channelId Int @map("channel_id")
status String @db.VarChar(50) // success/failed
errorMessage String? @map("error_message") @db.Text
createdAt DateTime @default(now()) @map("created_at")
report Report @relation(fields: [reportId], references: [id])
channel Channel @relation(fields: [channelId], references: [id])
@@index([reportId], map: "idx_report")
@@index([channelId], map: "idx_channel")
@@index([status], map: "idx_status")
@@map("push_logs")
}
// AI对话记录表
model Conversation {
id Int @id @default(autoincrement())
reportId Int? @map("report_id")
articleId Int? @map("article_id")
topicId Int @map("topic_id")
messages Json
userId Int? @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
report Report? @relation(fields: [reportId], references: [id])
article Article? @relation(fields: [articleId], references: [id])
topic Topic @relation(fields: [topicId], references: [id])
@@index([reportId], map: "idx_report")
@@index([articleId], map: "idx_article")
@@index([topicId], map: "idx_topic")
@@index([userId], map: "idx_user")
@@map("conversations")
}
+89
View File
@@ -0,0 +1,89 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
console.log('开始填充种子数据...');
// 创建默认 LLM 配置
const defaultLlmConfig = await prisma.llmConfig.create({
data: {
name: '默认配置',
baseUrl: 'https://api.openai.com/v1',
model: 'gpt-4o-mini',
apiKey: 'your-api-key-here',
enabled: true,
},
});
console.log('✅ 创建默认 LLM 配置:', defaultLlmConfig.id);
// 创建示例数据源
const sampleSource = await prisma.source.create({
data: {
name: '示例新闻源',
type: 'api',
config: JSON.stringify({
url: 'https://api.example.com/news',
method: 'GET',
headers: {},
}),
cronExpression: '0 */6 * * *',
enabled: false,
},
});
console.log('✅ 创建示例数据源:', sampleSource.id);
// 创建示例推送渠道
const sampleChannel = await prisma.channel.create({
data: {
name: '示例邮箱',
type: 'email',
config: JSON.stringify({
smtpHost: 'smtp.example.com',
smtpPort: 587,
username: 'user@example.com',
password: 'password',
to: 'recipient@example.com',
}),
enabled: false,
},
});
console.log('✅ 创建示例推送渠道:', sampleChannel.id);
// 创建示例主题
const sampleTopic = await prisma.topic.create({
data: {
name: '示例主题',
description: '这是一个示例主题,用于演示功能',
processMode: 'summary',
llmConfigId: defaultLlmConfig.id,
scheduleConfig: JSON.stringify({
cron: '0 9 * * *',
timezone: 'Asia/Shanghai',
}),
enabled: false,
topicSources: {
create: {
sourceId: sampleSource.id,
},
},
topicChannels: {
create: {
channelId: sampleChannel.id,
},
},
},
});
console.log('✅ 创建示例主题:', sampleTopic.id);
console.log('\n✨ 种子数据填充完成!');
}
main()
.catch((e) => {
console.error('❌ 种子数据填充失败:', e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+106
View File
@@ -0,0 +1,106 @@
import Fastify from 'fastify';
import cors from '@fastify/cors';
import { config, validateConfig } from './config';
import logger from './utils/logger';
// 验证配置
try {
validateConfig();
logger.info('配置验证通过');
} catch (error) {
logger.error('配置验证失败:', error);
process.exit(1);
}
// 创建 Fastify 实例
const app = Fastify({
logger: false, // 使用 winston 替代
});
// 注册插件
async function registerPlugins(): Promise<void> {
// CORS
await app.register(cors, {
origin: true,
credentials: true,
});
logger.info('CORS 插件已注册');
}
// 注册路由
async function registerRoutes(): Promise<void> {
// 健康检查
app.get('/api/v1/health', async () => {
return {
success: true,
data: {
status: 'ok',
timestamp: new Date().toISOString(),
version: '1.0.0',
},
};
});
logger.info('路由已注册');
}
// 错误处理
app.setErrorHandler((error, request, reply) => {
logger.error('请求处理错误:', {
error: error.message,
stack: error.stack,
url: request.url,
method: request.method,
});
reply.status(error.statusCode || 500).send({
success: false,
error: error.message || '服务器内部错误',
});
});
// 启动服务器
async function start(): Promise<void> {
try {
await registerPlugins();
await registerRoutes();
await app.listen({
port: config.port,
host: '0.0.0.0',
});
logger.info(`🚀 服务器启动成功,监听端口 ${config.port}`);
logger.info(`📚 API 文档: http://localhost:${config.port}/api/v1/health`);
} catch (error) {
logger.error('服务器启动失败:', error);
process.exit(1);
}
}
// 处理未捕获的异常
process.on('uncaughtException', (error) => {
logger.error('未捕获的异常:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
logger.error('未处理的 Promise 拒绝:', { reason, promise });
process.exit(1);
});
// 优雅关闭
process.on('SIGTERM', async () => {
logger.info('SIGTERM 信号收到,正在关闭服务器...');
await app.close();
process.exit(0);
});
process.on('SIGINT', async () => {
logger.info('SIGINT 信号收到,正在关闭服务器...');
await app.close();
process.exit(0);
});
// 启动
start();
+38
View File
@@ -0,0 +1,38 @@
import { PrismaClient } from '@prisma/client';
import { config } from '.';
import logger from '../utils/logger';
// 创建 Prisma 客户端实例
const prisma = new PrismaClient({
log: [
{ emit: 'event', level: 'query' },
{ emit: 'stdout', level: 'error' },
{ emit: 'stdout', level: 'info' },
{ emit: 'stdout', level: 'warn' },
],
});
// 查询日志
prisma.$on('query', (e: any) => {
logger.debug(`Query: ${e.query}`);
logger.debug(`Duration: ${e.duration}ms`);
});
// 连接数据库
export async function connectDatabase(): Promise<void> {
try {
await prisma.$connect();
logger.info('✅ 数据库连接成功');
} catch (error) {
logger.error('❌ 数据库连接失败:', error);
throw error;
}
}
// 断开数据库连接
export async function disconnectDatabase(): Promise<void> {
await prisma.$disconnect();
logger.info('数据库连接已关闭');
}
export default prisma;
+60
View File
@@ -0,0 +1,60 @@
import dotenv from 'dotenv';
import path from 'path';
// 加载环境变量
dotenv.config({ path: path.resolve(__dirname, '../../.env') });
export interface Config {
// 应用配置
nodeEnv: string;
port: number;
logLevel: string;
// 数据库配置
databaseUrl: string;
// 安全配置
jwtSecret?: string;
apiKey?: string;
}
function getEnvVar(key: string, defaultValue?: string): string {
const value = process.env[key] || defaultValue;
if (value === undefined) {
throw new Error(`环境变量 ${key} 未设置`);
}
return value;
}
function getEnvVarAsInt(key: string, defaultValue?: number): number {
const value = process.env[key];
if (value === undefined) {
if (defaultValue !== undefined) {
return defaultValue;
}
throw new Error(`环境变量 ${key} 未设置`);
}
const parsed = parseInt(value, 10);
if (isNaN(parsed)) {
throw new Error(`环境变量 ${key} 不是有效的整数`);
}
return parsed;
}
export const config: Config = {
nodeEnv: getEnvVar('NODE_ENV', 'development'),
port: getEnvVarAsInt('PORT', 3000),
logLevel: getEnvVar('LOG_LEVEL', 'info'),
databaseUrl: getEnvVar('DATABASE_URL'),
jwtSecret: process.env.JWT_SECRET,
apiKey: process.env.API_KEY,
};
// 验证必需配置
export function validateConfig(): void {
if (!config.databaseUrl) {
throw new Error('DATABASE_URL 是必需的配置项');
}
}
export default config;
+112
View File
@@ -0,0 +1,112 @@
import prisma from '../config/database';
import { NotFoundError, ConflictError } from '../utils/errors';
export abstract class BaseService<T, CreateInput, UpdateInput> {
protected model: any;
constructor(model: any) {
this.model = model;
}
// 获取所有记录
async findAll(options: {
skip?: number;
take?: number;
where?: any;
orderBy?: any;
include?: any;
} = {}): Promise<T[]> {
return this.model.findMany({
skip: options.skip,
take: options.take,
where: options.where,
orderBy: options.orderBy || { createdAt: 'desc' },
include: options.include,
});
}
// 根据 ID 查找
async findById(id: number, include?: any): Promise<T | null> {
return this.model.findUnique({
where: { id },
include,
});
}
// 根据 ID 查找(不存在则抛出错误)
async findByIdOrThrow(id: number, include?: any): Promise<T> {
const record = await this.findById(id, include);
if (!record) {
throw new NotFoundError(`${this.model.name} ID ${id} 不存在`);
}
return record;
}
// 创建记录
async create(data: CreateInput, uniqueFields?: string[]): Promise<T> {
// 检查唯一约束
if (uniqueFields && uniqueFields.length > 0) {
for (const field of uniqueFields) {
const value = (data as any)[field];
if (value !== undefined) {
const existing = await this.model.findFirst({
where: { [field]: value },
});
if (existing) {
throw new ConflictError(`${field} 已存在: ${value}`);
}
}
}
}
return this.model.create({ data });
}
// 更新记录
async update(id: number, data: UpdateInput): Promise<T> {
await this.findByIdOrThrow(id);
return this.model.update({
where: { id },
data,
});
}
// 删除记录
async delete(id: number): Promise<T> {
await this.findByIdOrThrow(id);
return this.model.delete({ where: { id } });
}
// 计数
async count(where?: any): Promise<number> {
return this.model.count({ where });
}
// 分页查询
async paginate(
page: number = 1,
limit: number = 20,
where?: any,
include?: any,
orderBy?: any
): Promise<{ data: T[]; total: number; totalPages: number }> {
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.model.findMany({
skip,
take: limit,
where,
include,
orderBy: orderBy || { createdAt: 'desc' },
}),
this.model.count({ where }),
]);
const totalPages = Math.ceil(total / limit);
return { data, total, totalPages };
}
}
export default BaseService;
+58
View File
@@ -0,0 +1,58 @@
// 通用类型定义
export interface ApiResponse<T = any> {
success: boolean;
data?: T;
error?: string;
message?: string;
}
export interface PaginationParams {
page: number;
limit: number;
}
export interface PaginatedResponse<T> extends ApiResponse<T[]> {
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
};
}
// 采集器类型
export interface CollectorConfig {
url: string;
method?: 'GET' | 'POST';
headers?: Record<string, string>;
body?: any;
}
export interface RawArticle {
title: string;
content?: string;
url?: string;
publishedAt?: Date;
[key: string]: any;
}
// 处理器类型
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis';
export interface ProcessingResult {
title: string;
content: string;
articleCount: number;
}
// 推送器类型
export interface PushConfig {
type: 'email' | 'dingtalk' | 'wechat' | 'slack';
config: Record<string, any>;
}
// 日志类型
export interface LogMetadata {
[key: string]: any;
}
+77
View File
@@ -0,0 +1,77 @@
// 自定义错误类
export class AppError extends Error {
public readonly statusCode: number;
public readonly isOperational: boolean;
constructor(
message: string,
statusCode: number = 500,
isOperational: boolean = true
) {
super(message);
this.statusCode = statusCode;
this.isOperational = isOperational;
Error.captureStackTrace(this, this.constructor);
}
}
// 400 - 错误请求
export class BadRequestError extends AppError {
constructor(message: string = '错误的请求') {
super(message, 400);
}
}
// 401 - 未授权
export class UnauthorizedError extends AppError {
constructor(message: string = '未授权访问') {
super(message, 401);
}
}
// 403 - 禁止访问
export class ForbiddenError extends AppError {
constructor(message: string = '禁止访问') {
super(message, 403);
}
}
// 404 - 未找到
export class NotFoundError extends AppError {
constructor(message: string = '资源未找到') {
super(message, 404);
}
}
// 409 - 冲突
export class ConflictError extends AppError {
constructor(message: string = '资源冲突') {
super(message, 409);
}
}
// 422 - 无法处理的实体
export class ValidationError extends AppError {
public readonly errors: Record<string, string>;
constructor(errors: Record<string, string>) {
super('请求参数验证失败', 422);
this.errors = errors;
}
}
// 500 - 服务器内部错误
export class InternalError extends AppError {
constructor(message: string = '服务器内部错误') {
super(message, 500, false);
}
}
// 503 - 服务不可用
export class ServiceUnavailableError extends AppError {
constructor(message: string = '服务暂时不可用') {
super(message, 503);
}
}
+85
View File
@@ -0,0 +1,85 @@
import winston from 'winston';
import path from 'path';
import { config } from '../config';
// 定义日志级别颜色
const colors = {
error: 'red',
warn: 'yellow',
info: 'green',
http: 'magenta',
debug: 'white',
};
winston.addColors(colors);
// 定义日志格式
const consoleFormat = winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.colorize({ all: true }),
winston.format.printf(
(info) => `${info.timestamp} [${info.level}]: ${info.message}`
)
);
const fileFormat = winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.json()
);
// 创建日志目录
const logDir = path.resolve(__dirname, '../../logs');
// 创建 logger 实例
const logger = winston.createLogger({
level: config.logLevel,
defaultMeta: { service: 'news-aggregator' },
transports: [
// 控制台输出
new winston.transports.Console({
format: consoleFormat,
}),
// 错误日志文件
new winston.transports.File({
filename: path.join(logDir, 'error.log'),
level: 'error',
format: fileFormat,
}),
// 所有日志文件
new winston.transports.File({
filename: path.join(logDir, 'combined.log'),
format: fileFormat,
}),
],
// 未捕获的异常处理
exceptionHandlers: [
new winston.transports.File({
filename: path.join(logDir, 'exceptions.log'),
}),
],
// 未处理的 Promise 拒绝
rejectionHandlers: [
new winston.transports.File({
filename: path.join(logDir, 'rejections.log'),
}),
],
});
// 开发环境下简化日志输出
if (config.nodeEnv === 'development') {
logger.clear();
logger.add(
new winston.transports.Console({
format: consoleFormat,
})
);
}
// 流接口用于 HTTP 请求日志
export const stream = {
write: (message: string): void => {
logger.http(message.trim());
},
};
export default logger;
+61
View File
@@ -0,0 +1,61 @@
import { FastifyReply } from 'fastify';
import { ApiResponse, PaginatedResponse } from '../types';
export function successResponse<T>(
reply: FastifyReply,
data: T,
message?: string,
statusCode: number = 200
): void {
const response: ApiResponse<T> = {
success: true,
data,
message,
};
reply.status(statusCode).send(response);
}
export function paginatedResponse<T>(
reply: FastifyReply,
data: T[],
total: number,
page: number,
limit: number
): void {
const totalPages = Math.ceil(total / limit);
const response: PaginatedResponse<T> = {
success: true,
data,
pagination: {
page,
limit,
total,
totalPages,
},
};
reply.status(200).send(response);
}
export function errorResponse(
reply: FastifyReply,
error: string,
statusCode: number = 500
): void {
const response: ApiResponse = {
success: false,
error,
};
reply.status(statusCode).send(response);
}
export function createdResponse<T>(
reply: FastifyReply,
data: T,
message: string = '创建成功'
): void {
successResponse(reply, data, message, 201);
}
export function noContentResponse(reply: FastifyReply): void {
reply.status(204).send();
}
+69
View File
@@ -0,0 +1,69 @@
import { BadRequestError, ValidationError } from './errors';
export function validateRequired(
data: Record<string, any>,
fields: string[]
): void {
const missing: string[] = [];
for (const field of fields) {
if (data[field] === undefined || data[field] === null || data[field] === '') {
missing.push(field);
}
}
if (missing.length > 0) {
throw new BadRequestError(`缺少必需字段: ${missing.join(', ')}`);
}
}
export function validateEmail(email: string): void {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new BadRequestError('邮箱格式不正确');
}
}
export function validateUrl(url: string): void {
try {
new URL(url);
} catch {
throw new BadRequestError('URL 格式不正确');
}
}
export function validateCronExpression(cron: string): void {
const cronRegex = /^((\*|\?|\d+([\/\-]\d+)?)(,\d+([\/\-]\d+)?)*\s+){4}(\*|\?|\d+([\/\-]\d+)?)(,\d+([\/\-]\d+)?)*$/;
if (!cronRegex.test(cron)) {
throw new BadRequestError('Cron 表达式格式不正确');
}
}
export function validateJson(jsonString: string): any {
try {
return JSON.parse(jsonString);
} catch {
throw new BadRequestError('JSON 格式不正确');
}
}
export function sanitizeString(input: string, maxLength: number = 255): string {
if (typeof input !== 'string') {
return '';
}
return input.trim().slice(0, maxLength);
}
export function validatePagination(
page: any,
limit: any,
maxLimit: number = 100
): { page: number; limit: number } {
const parsedPage = parseInt(page, 10) || 1;
const parsedLimit = Math.min(parseInt(limit, 10) || 20, maxLimit);
return {
page: Math.max(1, parsedPage),
limit: Math.max(1, parsedLimit),
};
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}