完成内容: - 创建前后端项目目录结构 - 初始化 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>
698 lines
12 KiB
Markdown
698 lines
12 KiB
Markdown
# 开发指南
|
||
|
||
本文档提供 News Aggregator 项目的开发指南和最佳实践。
|
||
|
||
## 目录
|
||
|
||
- [快速开始](#快速开始)
|
||
- [开发流程](#开发流程)
|
||
- [代码规范](#代码规范)
|
||
- [测试指南](#测试指南)
|
||
- [调试技巧](#调试技巧)
|
||
- [常见问题](#常见问题)
|
||
|
||
## 快速开始
|
||
|
||
### 环境准备
|
||
|
||
1. **安装 Node.js**
|
||
- 版本:20.x 或更高
|
||
- 下载:https://nodejs.org/
|
||
|
||
2. **安装 MySQL**
|
||
- 版本:5.6 或更高
|
||
- 创建数据库:`news_aggregator`
|
||
|
||
3. **安装 PM2**(生产环境)
|
||
```bash
|
||
npm install -g pm2
|
||
```
|
||
|
||
### 项目初始化
|
||
|
||
```bash
|
||
# 1. 克隆项目
|
||
git clone <repository-url>
|
||
cd news-aggregator
|
||
|
||
# 2. 安装后端依赖
|
||
cd backend
|
||
npm install
|
||
|
||
# 3. 配置环境变量
|
||
cp .env.example .env
|
||
# 编辑 .env 文件,配置数据库连接等
|
||
|
||
# 4. 初始化数据库
|
||
npm run prisma:migrate
|
||
npm run prisma:seed
|
||
|
||
# 5. 启动后端开发服务
|
||
npm run dev
|
||
|
||
# 6. 安装前端依赖(新终端)
|
||
cd ../frontend
|
||
npm install
|
||
|
||
# 7. 启动前端开发服务
|
||
npm run dev
|
||
```
|
||
|
||
### 访问应用
|
||
|
||
- 后端 API:http://localhost:3000
|
||
- 前端界面:http://localhost:5173
|
||
- API 文档:http://localhost:3000/api/health
|
||
- Prisma Studio:`npm run prisma:studio`
|
||
|
||
## 开发流程
|
||
|
||
### 1. 任务开发流程
|
||
|
||
```
|
||
选择任务 → 阅读文档 → 实现功能 → 测试验证 → 提交代码
|
||
```
|
||
|
||
#### 步骤详解
|
||
|
||
1. **选择任务**
|
||
- 查看 [任务清单](./tasks/README.md)
|
||
- 选择下一个待完成的任务
|
||
- 确认前置任务已完成
|
||
|
||
2. **阅读文档**
|
||
- 阅读任务文档
|
||
- 理解任务目标和要求
|
||
- 查看相关设计文档
|
||
|
||
3. **实现功能**
|
||
- 按任务文档步骤实现
|
||
- 遵循代码规范
|
||
- 编写清晰的注释
|
||
|
||
4. **测试验证**
|
||
- 运行任务文档中的验证步骤
|
||
- 测试边界情况
|
||
- 确保功能正常
|
||
|
||
5. **提交代码**
|
||
- 编写清晰的提交信息
|
||
- 提交到 Git
|
||
- 更新任务状态
|
||
|
||
### 2. 分支管理
|
||
|
||
```
|
||
main (主分支)
|
||
├── develop (开发分支)
|
||
│ ├── feature/task-01 (功能分支)
|
||
│ ├── feature/task-02
|
||
│ └── ...
|
||
└── hotfix/xxx (热修复分支)
|
||
```
|
||
|
||
#### 分支命名规范
|
||
|
||
- `feature/task-xx`:功能开发
|
||
- `fix/bug-description`:Bug 修复
|
||
- `hotfix/critical-issue`:紧急修复
|
||
- `refactor/module-name`:重构
|
||
|
||
#### 工作流程
|
||
|
||
```bash
|
||
# 1. 创建功能分支
|
||
git checkout -b feature/task-01
|
||
|
||
# 2. 开发功能
|
||
# ... 编写代码 ...
|
||
|
||
# 3. 提交代码
|
||
git add .
|
||
git commit -m "feat: implement task 01"
|
||
|
||
# 4. 推送到远程
|
||
git push origin feature/task-01
|
||
|
||
# 5. 创建 Pull Request
|
||
# 在 GitHub/GitLab 上创建 PR
|
||
|
||
# 6. 代码审查通过后合并
|
||
git checkout develop
|
||
git merge feature/task-01
|
||
```
|
||
|
||
### 3. 提交规范
|
||
|
||
#### 提交信息格式
|
||
|
||
```
|
||
<type>(<scope>): <subject>
|
||
|
||
<body>
|
||
|
||
<footer>
|
||
```
|
||
|
||
#### Type 类型
|
||
|
||
- `feat`: 新功能
|
||
- `fix`: Bug 修复
|
||
- `docs`: 文档更新
|
||
- `style`: 代码格式(不影响功能)
|
||
- `refactor`: 重构
|
||
- `test`: 测试相关
|
||
- `chore`: 构建/工具相关
|
||
|
||
#### 示例
|
||
|
||
```bash
|
||
# 新功能
|
||
git commit -m "feat(collector): add API collector"
|
||
|
||
# Bug 修复
|
||
git commit -m "fix(report): fix date format issue"
|
||
|
||
# 文档更新
|
||
git commit -m "docs: update API documentation"
|
||
|
||
# 重构
|
||
git commit -m "refactor(service): simplify report generation logic"
|
||
```
|
||
|
||
## 代码规范
|
||
|
||
### TypeScript 规范
|
||
|
||
#### 1. 类型定义
|
||
|
||
```typescript
|
||
// ✅ 好的做法
|
||
interface User {
|
||
id: number
|
||
name: string
|
||
email: string
|
||
}
|
||
|
||
function getUser(id: number): Promise<User> {
|
||
// ...
|
||
}
|
||
|
||
// ❌ 避免使用 any
|
||
function getUser(id: any): any {
|
||
// ...
|
||
}
|
||
```
|
||
|
||
#### 2. 命名规范
|
||
|
||
```typescript
|
||
// 变量/函数:camelCase
|
||
const userName = 'John'
|
||
function getUserName() {}
|
||
|
||
// 类/接口:PascalCase
|
||
class UserService {}
|
||
interface UserConfig {}
|
||
|
||
// 常量:UPPER_SNAKE_CASE
|
||
const API_BASE_URL = 'http://localhost:3000'
|
||
|
||
// 私有成员:前缀下划线
|
||
class User {
|
||
private _password: string
|
||
}
|
||
```
|
||
|
||
#### 3. 函数规范
|
||
|
||
```typescript
|
||
// ✅ 好的做法:清晰的函数签名
|
||
async function createUser(
|
||
name: string,
|
||
email: string,
|
||
options?: { sendEmail?: boolean }
|
||
): Promise<User> {
|
||
// ...
|
||
}
|
||
|
||
// ✅ 好的做法:使用解构
|
||
function processUser({ id, name, email }: User) {
|
||
// ...
|
||
}
|
||
|
||
// ❌ 避免:参数过多
|
||
function createUser(name, email, age, phone, address, city, country) {
|
||
// ...
|
||
}
|
||
```
|
||
|
||
#### 4. 异步处理
|
||
|
||
```typescript
|
||
// ✅ 好的做法:使用 async/await
|
||
async function fetchData() {
|
||
try {
|
||
const data = await api.get('/data')
|
||
return data
|
||
} catch (error) {
|
||
logger.error('Failed to fetch data', error)
|
||
throw error
|
||
}
|
||
}
|
||
|
||
// ❌ 避免:回调地狱
|
||
function fetchData(callback) {
|
||
api.get('/data', (err, data) => {
|
||
if (err) {
|
||
callback(err)
|
||
} else {
|
||
processData(data, (err, result) => {
|
||
// ...
|
||
})
|
||
}
|
||
})
|
||
}
|
||
```
|
||
|
||
### Vue 规范
|
||
|
||
#### 1. 组件命名
|
||
|
||
```typescript
|
||
// ✅ 好的做法:PascalCase
|
||
<template>
|
||
<UserProfile />
|
||
<ArticleList />
|
||
</template>
|
||
|
||
// ❌ 避免:kebab-case(在 script 中)
|
||
<template>
|
||
<user-profile />
|
||
</template>
|
||
```
|
||
|
||
#### 2. Props 定义
|
||
|
||
```typescript
|
||
// ✅ 好的做法:完整的类型定义
|
||
interface Props {
|
||
userId: number
|
||
userName: string
|
||
isActive?: boolean
|
||
}
|
||
|
||
const props = defineProps<Props>()
|
||
|
||
// ❌ 避免:无类型定义
|
||
const props = defineProps(['userId', 'userName'])
|
||
```
|
||
|
||
#### 3. 组件结构
|
||
|
||
```vue
|
||
<template>
|
||
<!-- 模板 -->
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
// 1. 导入
|
||
import { ref, computed, onMounted } from 'vue'
|
||
|
||
// 2. Props/Emits
|
||
interface Props {
|
||
// ...
|
||
}
|
||
const props = defineProps<Props>()
|
||
const emit = defineEmits<{
|
||
update: [value: string]
|
||
}>()
|
||
|
||
// 3. 响应式数据
|
||
const count = ref(0)
|
||
|
||
// 4. 计算属性
|
||
const doubleCount = computed(() => count.value * 2)
|
||
|
||
// 5. 方法
|
||
function increment() {
|
||
count.value++
|
||
}
|
||
|
||
// 6. 生命周期
|
||
onMounted(() => {
|
||
// ...
|
||
})
|
||
</script>
|
||
|
||
<style scoped>
|
||
/* 样式 */
|
||
</style>
|
||
```
|
||
|
||
### 代码注释
|
||
|
||
#### 1. 文件头注释
|
||
|
||
```typescript
|
||
/**
|
||
* 用户服务
|
||
*
|
||
* 提供用户相关的业务逻辑
|
||
*
|
||
* @module services/user
|
||
*/
|
||
```
|
||
|
||
#### 2. 函数注释
|
||
|
||
```typescript
|
||
/**
|
||
* 创建用户
|
||
*
|
||
* @param name - 用户名
|
||
* @param email - 邮箱
|
||
* @returns 创建的用户对象
|
||
* @throws {ValidationError} 参数验证失败
|
||
*/
|
||
async function createUser(name: string, email: string): Promise<User> {
|
||
// ...
|
||
}
|
||
```
|
||
|
||
#### 3. 复杂逻辑注释
|
||
|
||
```typescript
|
||
// 计算用户的活跃度分数
|
||
// 规则:
|
||
// 1. 基础分 = 登录天数 * 10
|
||
// 2. 发帖加分 = 发帖数 * 5
|
||
// 3. 评论加分 = 评论数 * 2
|
||
const activityScore =
|
||
loginDays * 10 +
|
||
postCount * 5 +
|
||
commentCount * 2
|
||
```
|
||
|
||
## 测试指南
|
||
|
||
### 单元测试
|
||
|
||
```typescript
|
||
// 示例:测试工具函数
|
||
import { describe, it, expect } from 'vitest'
|
||
import { formatDate } from '@/utils/date'
|
||
|
||
describe('formatDate', () => {
|
||
it('should format date correctly', () => {
|
||
const date = new Date('2024-01-01')
|
||
expect(formatDate(date)).toBe('2024-01-01')
|
||
})
|
||
|
||
it('should handle null', () => {
|
||
expect(formatDate(null)).toBe('')
|
||
})
|
||
})
|
||
```
|
||
|
||
### API 测试
|
||
|
||
```bash
|
||
# 使用 curl 测试
|
||
curl http://localhost:3000/api/health
|
||
|
||
# 使用 REST Client(VS Code 插件)
|
||
# 在 .http 文件中编写请求
|
||
GET http://localhost:3000/api/health
|
||
```
|
||
|
||
### 端到端测试
|
||
|
||
```typescript
|
||
// 使用 Playwright 进行 E2E 测试
|
||
import { test, expect } from '@playwright/test'
|
||
|
||
test('should display dashboard', async ({ page }) => {
|
||
await page.goto('http://localhost:5173')
|
||
await expect(page.locator('h1')).toContainText('仪表盘')
|
||
})
|
||
```
|
||
|
||
## 调试技巧
|
||
|
||
### 后端调试
|
||
|
||
#### 1. 使用日志
|
||
|
||
```typescript
|
||
import { logger } from './utils/logger'
|
||
|
||
// 不同级别的日志
|
||
logger.debug('Debug message', { data })
|
||
logger.info('Info message')
|
||
logger.warn('Warning message')
|
||
logger.error('Error message', error)
|
||
```
|
||
|
||
#### 2. 使用断点
|
||
|
||
在 VS Code 中配置 `.vscode/launch.json`:
|
||
|
||
```json
|
||
{
|
||
"version": "0.2.0",
|
||
"configurations": [
|
||
{
|
||
"type": "node",
|
||
"request": "launch",
|
||
"name": "Debug Backend",
|
||
"runtimeExecutable": "npm",
|
||
"runtimeArgs": ["run", "dev"],
|
||
"cwd": "${workspaceFolder}/backend",
|
||
"console": "integratedTerminal"
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
#### 3. 查看数据库
|
||
|
||
```bash
|
||
# 使用 Prisma Studio
|
||
cd backend
|
||
npm run prisma:studio
|
||
```
|
||
|
||
### 前端调试
|
||
|
||
#### 1. Vue DevTools
|
||
|
||
安装 Vue DevTools 浏览器插件,可以:
|
||
- 查看组件树
|
||
- 检查组件状态
|
||
- 查看 Pinia store
|
||
- 追踪事件
|
||
|
||
#### 2. 网络请求
|
||
|
||
在浏览器开发者工具的 Network 标签中:
|
||
- 查看 API 请求
|
||
- 检查请求参数
|
||
- 查看响应数据
|
||
- 分析请求时间
|
||
|
||
#### 3. 控制台调试
|
||
|
||
```typescript
|
||
// 在代码中添加 console.log
|
||
console.log('User data:', userData)
|
||
|
||
// 使用 debugger 语句
|
||
function processData(data) {
|
||
debugger // 浏览器会在此处暂停
|
||
// ...
|
||
}
|
||
```
|
||
|
||
## 常见问题
|
||
|
||
### 后端问题
|
||
|
||
#### Q1: 数据库连接失败
|
||
**A**: 检查以下几点:
|
||
1. MySQL 服务是否运行
|
||
2. `.env` 中的数据库配置是否正确
|
||
3. 数据库是否已创建
|
||
4. 用户权限是否足够
|
||
|
||
#### Q2: Prisma 迁移失败
|
||
**A**: 尝试以下方法:
|
||
```bash
|
||
# 重置数据库
|
||
npm run prisma:migrate reset
|
||
|
||
# 重新生成 Prisma Client
|
||
npm run prisma:generate
|
||
```
|
||
|
||
#### Q3: 采集器不工作
|
||
**A**: 检查:
|
||
1. 数据源配置是否正确
|
||
2. 网络连接是否正常
|
||
3. 查看采集日志
|
||
4. 检查 cron 表达式
|
||
|
||
### 前端问题
|
||
|
||
#### Q1: API 请求 CORS 错误
|
||
**A**: 确保后端已配置 CORS:
|
||
```typescript
|
||
// backend/src/app.ts
|
||
await app.register(cors, {
|
||
origin: 'http://localhost:5173',
|
||
credentials: true,
|
||
})
|
||
```
|
||
|
||
#### Q2: 路由 404
|
||
**A**: 检查:
|
||
1. 路由配置是否正确
|
||
2. 组件路径是否存在
|
||
3. 是否使用了懒加载
|
||
|
||
#### Q3: 组件样式不生效
|
||
**A**: 检查:
|
||
1. 是否使用了 `scoped`
|
||
2. CSS 选择器是否正确
|
||
3. 是否有样式冲突
|
||
|
||
## 性能优化
|
||
|
||
### 后端优化
|
||
|
||
1. **数据库查询优化**
|
||
```typescript
|
||
// ✅ 使用索引
|
||
// ✅ 避免 N+1 查询
|
||
// ✅ 使用分页
|
||
const users = await prisma.user.findMany({
|
||
where: { active: true },
|
||
include: { posts: true },
|
||
skip: (page - 1) * limit,
|
||
take: limit,
|
||
})
|
||
```
|
||
|
||
2. **缓存策略**
|
||
```typescript
|
||
// 缓存常用数据
|
||
const cache = new Map()
|
||
|
||
async function getConfig(key: string) {
|
||
if (cache.has(key)) {
|
||
return cache.get(key)
|
||
}
|
||
const value = await fetchConfig(key)
|
||
cache.set(key, value)
|
||
return value
|
||
}
|
||
```
|
||
|
||
### 前端优化
|
||
|
||
1. **路由懒加载**
|
||
```typescript
|
||
const routes = [
|
||
{
|
||
path: '/reports',
|
||
component: () => import('@/views/reports/ReportList.vue'),
|
||
},
|
||
]
|
||
```
|
||
|
||
2. **组件按需加载**
|
||
```typescript
|
||
// 只导入需要的组件
|
||
import { ElButton, ElTable } from 'element-plus'
|
||
```
|
||
|
||
3. **列表虚拟滚动**
|
||
```vue
|
||
<template>
|
||
<el-table-v2
|
||
:columns="columns"
|
||
:data="data"
|
||
:width="700"
|
||
:height="400"
|
||
/>
|
||
</template>
|
||
```
|
||
|
||
## 安全最佳实践
|
||
|
||
### 1. 输入验证
|
||
|
||
```typescript
|
||
// ✅ 验证用户输入
|
||
function createUser(data: any) {
|
||
if (!data.email || !isValidEmail(data.email)) {
|
||
throw new ValidationError('Invalid email')
|
||
}
|
||
// ...
|
||
}
|
||
```
|
||
|
||
### 2. SQL 注入防护
|
||
|
||
```typescript
|
||
// ✅ 使用 Prisma(自动防护)
|
||
await prisma.user.findMany({
|
||
where: { email: userInput },
|
||
})
|
||
|
||
// ❌ 避免拼接 SQL
|
||
const sql = `SELECT * FROM users WHERE email = '${userInput}'`
|
||
```
|
||
|
||
### 3. XSS 防护
|
||
|
||
```vue
|
||
<!-- ✅ Vue 自动转义 -->
|
||
<div>{{ userInput }}</div>
|
||
|
||
<!-- ❌ 避免使用 v-html(除非必要) -->
|
||
<div v-html="userInput"></div>
|
||
```
|
||
|
||
### 4. 敏感信息保护
|
||
|
||
```typescript
|
||
// ✅ 使用环境变量
|
||
const apiKey = process.env.API_KEY
|
||
|
||
// ❌ 避免硬编码
|
||
const apiKey = 'sk-1234567890'
|
||
```
|
||
|
||
## 参考资源
|
||
|
||
### 官方文档
|
||
- [TypeScript](https://www.typescriptlang.org/docs/)
|
||
- [Vue 3](https://vuejs.org/)
|
||
- [Fastify](https://www.fastify.io/)
|
||
- [Prisma](https://www.prisma.io/docs)
|
||
- [Element Plus](https://element-plus.org/)
|
||
|
||
### 工具
|
||
- [VS Code](https://code.visualstudio.com/)
|
||
- [Postman](https://www.postman.com/)
|
||
- [Prisma Studio](https://www.prisma.io/studio)
|
||
|
||
### 社区
|
||
- [Stack Overflow](https://stackoverflow.com/)
|
||
- [GitHub Discussions](https://github.com/)
|
||
|
||
---
|
||
|
||
**持续更新中...**
|