完成内容: - 创建前后端项目目录结构 - 初始化 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>
12 KiB
12 KiB
任务 03:后端核心框架
任务概述
搭建后端核心框架,包括 Fastify 应用初始化、配置管理、中间件、错误处理等基础设施。
前置条件
- 任务 01、02 已完成
- 数据库已初始化
任务目标
- 创建 Fastify 应用
- 配置管理
- 统一响应格式
- 错误处理中间件
- 日志系统
- 基础 API 路由
详细步骤
1. 创建配置管理
创建 backend/src/config/index.ts:
import dotenv from 'dotenv'
dotenv.config()
export const config = {
// 应用配置
app: {
env: process.env.NODE_ENV || 'development',
port: parseInt(process.env.PORT || '3000', 10),
host: process.env.HOST || '0.0.0.0',
},
// 数据库配置
database: {
url: process.env.DATABASE_URL || '',
},
// 日志配置
log: {
level: process.env.LOG_LEVEL || 'info',
},
// CORS 配置
cors: {
origin: process.env.CORS_ORIGIN || '*',
credentials: true,
},
}
// 验证必需的环境变量
function validateConfig() {
const required = ['DATABASE_URL']
const missing = required.filter((key) => !process.env[key])
if (missing.length > 0) {
throw new Error(`缺少必需的环境变量: ${missing.join(', ')}`)
}
}
validateConfig()
2. 创建类型定义
创建 backend/src/types/api.ts:
// 统一响应格式
export interface ApiResponse<T = any> {
success: boolean
data?: T
error?: ApiError
message?: string
}
export interface ApiError {
code: string
message: string
details?: any
}
// 分页参数
export interface PaginationParams {
page?: number
limit?: number
}
// 分页响应
export interface PaginatedResponse<T> {
items: T[]
total: number
page: number
limit: number
totalPages: number
}
创建 backend/src/types/index.ts:
export * from './api'
3. 创建工具函数
创建 backend/src/utils/response.ts:
import type { ApiResponse, ApiError } from '../types'
export class ResponseHelper {
static success<T>(data?: T, message?: string): ApiResponse<T> {
return {
success: true,
data,
message,
}
}
static error(code: string, message: string, details?: any): ApiResponse {
return {
success: false,
error: {
code,
message,
details,
},
}
}
}
创建 backend/src/utils/logger.ts:
import { config } from '../config'
type LogLevel = 'debug' | 'info' | 'warn' | 'error'
class Logger {
private shouldLog(level: LogLevel): boolean {
const levels: LogLevel[] = ['debug', 'info', 'warn', 'error']
const configLevel = config.log.level as LogLevel
return levels.indexOf(level) >= levels.indexOf(configLevel)
}
private formatMessage(level: LogLevel, message: string, meta?: any): string {
const timestamp = new Date().toISOString()
const metaStr = meta ? ` ${JSON.stringify(meta)}` : ''
return `[${timestamp}] [${level.toUpperCase()}] ${message}${metaStr}`
}
debug(message: string, meta?: any) {
if (this.shouldLog('debug')) {
console.debug(this.formatMessage('debug', message, meta))
}
}
info(message: string, meta?: any) {
if (this.shouldLog('info')) {
console.info(this.formatMessage('info', message, meta))
}
}
warn(message: string, meta?: any) {
if (this.shouldLog('warn')) {
console.warn(this.formatMessage('warn', message, meta))
}
}
error(message: string, meta?: any) {
if (this.shouldLog('error')) {
console.error(this.formatMessage('error', message, meta))
}
}
}
export const logger = new Logger()
4. 创建错误处理
创建 backend/src/utils/errors.ts:
export class AppError extends Error {
constructor(
public code: string,
message: string,
public statusCode: number = 500,
public details?: any
) {
super(message)
this.name = 'AppError'
}
}
export class ValidationError extends AppError {
constructor(message: string, details?: any) {
super('VALIDATION_ERROR', message, 400, details)
this.name = 'ValidationError'
}
}
export class NotFoundError extends AppError {
constructor(resource: string) {
super('NOT_FOUND', `${resource} not found`, 404)
this.name = 'NotFoundError'
}
}
export class UnauthorizedError extends AppError {
constructor(message: string = 'Unauthorized') {
super('UNAUTHORIZED', message, 401)
this.name = 'UnauthorizedError'
}
}
export class ForbiddenError extends AppError {
constructor(message: string = 'Forbidden') {
super('FORBIDDEN', message, 403)
this.name = 'ForbiddenError'
}
}
5. 创建中间件
创建 backend/src/web/middleware/error-handler.ts:
import type { FastifyError, FastifyReply, FastifyRequest } from 'fastify'
import { AppError } from '../../utils/errors'
import { ResponseHelper } from '../../utils/response'
import { logger } from '../../utils/logger'
export async function errorHandler(
error: FastifyError,
request: FastifyRequest,
reply: FastifyReply
) {
logger.error('Request error', {
method: request.method,
url: request.url,
error: error.message,
stack: error.stack,
})
// 处理自定义错误
if (error instanceof AppError) {
return reply.status(error.statusCode).send(
ResponseHelper.error(error.code, error.message, error.details)
)
}
// 处理 Fastify 验证错误
if (error.validation) {
return reply.status(400).send(
ResponseHelper.error('VALIDATION_ERROR', 'Validation failed', error.validation)
)
}
// 处理未知错误
return reply.status(500).send(
ResponseHelper.error(
'INTERNAL_ERROR',
'Internal server error',
process.env.NODE_ENV === 'development' ? error.message : undefined
)
)
}
创建 backend/src/web/middleware/request-logger.ts:
import type { FastifyRequest, FastifyReply } from 'fastify'
import { logger } from '../../utils/logger'
export async function requestLogger(request: FastifyRequest, reply: FastifyReply) {
const start = Date.now()
reply.addHook('onSend', async () => {
const duration = Date.now() - start
logger.info('Request completed', {
method: request.method,
url: request.url,
statusCode: reply.statusCode,
duration: `${duration}ms`,
})
})
}
6. 创建健康检查路由
创建 backend/src/web/routes/health.ts:
import type { FastifyInstance } from 'fastify'
import { ResponseHelper } from '../../utils/response'
import prisma from '../../utils/prisma'
export async function healthRoutes(app: FastifyInstance) {
// 基础健康检查
app.get('/health', async () => {
return ResponseHelper.success({
status: 'ok',
timestamp: new Date().toISOString(),
})
})
// 详细健康检查(包括数据库)
app.get('/health/detailed', async () => {
try {
// 检查数据库连接
await prisma.$queryRaw`SELECT 1`
return ResponseHelper.success({
status: 'ok',
timestamp: new Date().toISOString(),
services: {
database: 'ok',
},
})
} catch (error) {
return ResponseHelper.error('HEALTH_CHECK_FAILED', 'Health check failed', {
database: 'error',
})
}
})
}
7. 创建 Fastify 应用
创建 backend/src/app.ts:
import Fastify from 'fastify'
import cors from '@fastify/cors'
import { config } from './config'
import { logger } from './utils/logger'
import { errorHandler } from './web/middleware/error-handler'
import { requestLogger } from './web/middleware/request-logger'
import { healthRoutes } from './web/routes/health'
export async function createApp() {
const app = Fastify({
logger: false, // 使用自定义 logger
})
// 注册 CORS
await app.register(cors, {
origin: config.cors.origin,
credentials: config.cors.credentials,
})
// 注册中间件
app.addHook('onRequest', requestLogger)
// 注册错误处理
app.setErrorHandler(errorHandler)
// 注册路由
await app.register(healthRoutes, { prefix: '/api' })
return app
}
export async function startServer() {
try {
const app = await createApp()
await app.listen({
port: config.app.port,
host: config.app.host,
})
logger.info(`Server started on http://${config.app.host}:${config.app.port}`)
logger.info(`Environment: ${config.app.env}`)
} catch (error) {
logger.error('Failed to start server', error)
process.exit(1)
}
}
// 如果直接运行此文件,则启动服务器
if (require.main === module) {
startServer()
}
8. 更新 package.json
确保 backend/package.json 中的 scripts 正确:
{
"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",
"prisma:seed": "tsx prisma/seed.ts"
}
}
9. 创建 API 测试脚本
创建 backend/test-api.http(使用 REST Client 插件):
### 健康检查
GET http://localhost:3000/api/health
### 详细健康检查
GET http://localhost:3000/api/health/detailed
验证步骤
1. 启动开发服务器
cd backend
npm run dev
应该看到:
[2024-01-01T10:00:00.000Z] [INFO] Server started on http://0.0.0.0:3000
[2024-01-01T10:00:00.000Z] [INFO] Environment: development
2. 测试健康检查 API
# 基础健康检查
curl http://localhost:3000/api/health
# 预期响应
{
"success": true,
"data": {
"status": "ok",
"timestamp": "2024-01-01T10:00:00.000Z"
}
}
# 详细健康检查
curl http://localhost:3000/api/health/detailed
# 预期响应
{
"success": true,
"data": {
"status": "ok",
"timestamp": "2024-01-01T10:00:00.000Z",
"services": {
"database": "ok"
}
}
}
3. 测试错误处理
访问不存在的路由:
curl http://localhost:3000/api/not-found
# 预期响应(404)
{
"success": false,
"error": {
"code": "NOT_FOUND",
"message": "Route GET:/api/not-found not found"
}
}
4. 检查日志输出
在控制台应该能看到请求日志:
[2024-01-01T10:00:00.000Z] [INFO] Request completed {"method":"GET","url":"/api/health","statusCode":200,"duration":"5ms"}
预期产物
- ✅ Fastify 应用创建完成
- ✅ 配置管理系统完成
- ✅ 统一响应格式实现
- ✅ 错误处理中间件完成
- ✅ 日志系统完成
- ✅ 健康检查 API 完成
- ✅ 服务器可以正常启动和响应请求
项目结构
完成后的目录结构:
backend/
├── src/
│ ├── config/
│ │ └── index.ts # 配置管理
│ ├── types/
│ │ ├── api.ts # API 类型定义
│ │ └── index.ts
│ ├── utils/
│ │ ├── prisma.ts # Prisma 客户端
│ │ ├── response.ts # 响应工具
│ │ ├── logger.ts # 日志工具
│ │ └── errors.ts # 错误类
│ ├── web/
│ │ ├── middleware/
│ │ │ ├── error-handler.ts # 错误处理
│ │ │ └── request-logger.ts # 请求日志
│ │ └── routes/
│ │ └── health.ts # 健康检查路由
│ └── app.ts # 应用入口
├── prisma/
│ ├── schema.prisma
│ └── seed.ts
├── .env
├── .env.example
├── package.json
└── tsconfig.json
下一步
完成本任务后,继续 任务 04:采集器实现。