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

完成内容:
- 创建前后端项目目录结构
- 初始化 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

+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),
};
}