Skip to content

开发流程与常见任务

参与 TodoHeap 开发的流程、工作流程和常见任务解决方案。


开发工作流

功能开发周期

1. 理解需求

2. 设计方案

3. 实现代码
   ├─ 后端优先(如果有 Edge Function)
   └─ 前端接入

4. 本地测试
   ├─ 单元测试
   └─ 手动测试

5. 提交 PR

6. 代码审查

7. 合并与部署

前端开发流程

1. 理解需求

查看相关的需求或 Issue:

bash
# 查看项目 Issues
https://github.com/sherlocknieh/TodoHeap/issues

# 查看需求文档
docs/zh/dev/02.需求文档.md

2. 设计 UI/UX

  • 查看现有组件:frontend/src/components/
  • 参考 TailwindCSS 色系与设计规范
  • 检查深色模式兼容性

3. 编写组件

bash
# 在 frontend/src/components/ 创建新组件
# 例如:MyNewComponent.vue

# 编写 Vue 3 Composition API 风格代码
<template>
  <!-- 模板 -->
</template>

<script setup lang="ts">
// 逻辑
</script>

<style scoped>
/* 样式 */
</style>

4. 集成状态管理

typescript
// 在 store 中获取或修改状态
import { useTodosStore } from '../stores/todos'

const todosStore = useTodosStore()
const todos = todosStore.todos  // 读
todosStore.addTodo(...)          // 写

5. 测试

bash
# 运行单元测试
pnpm test

# 监视模式
pnpm test:watch

# 类型检查
pnpm type-check

后端开发流程(Edge Function)

1. 创建函数目录

bash
cd supabase/functions
mkdir my_new_function
cd my_new_function

# 创建必要文件
touch index.ts deno.json

2. 配置 deno.json

json
{
  "imports": {
    "supabase": "https://esm.sh/@supabase/supabase-js@2",
    "cors": "../_shared/cors.ts"
  },
  "compilerOptions": {
    "lib": ["deno.window"]
  }
}

3. 实现函数逻辑

typescript
// index.ts
import { cors } from "../_shared/cors.ts";

Deno.serve(async (req: Request) => {
  // 处理 CORS
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: cors() });
  }

  try {
    const { query } = await req.json();
    
    // 你的业务逻辑
    const result = processQuery(query);
    
    return new Response(
      JSON.stringify({ success: true, data: result }),
      {
        headers: { ...cors(), "Content-Type": "application/json" },
        status: 200,
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({ success: false, error: error.message }),
      { headers: cors(), status: 400 }
    );
  }
});

4. 本地测试

bash
# 启动 Edge Functions 开发服务
supabase functions serve --no-verify-jwt

# 测试函数(新终端)
curl -X POST http://localhost:54321/functions/v1/my_new_function \
  -H "Content-Type: application/json" \
  -d '{"query":"test"}'

5. 部署

bash
# 部署到 Supabase
supabase functions deploy my_new_function

# 查看日志
supabase functions logs my_new_function

常见任务

前端任务

添加新的 UI 组件

bash
# 1. 在 frontend/src/components/ 创建组件
# 2. 遵循现有组件的结构
# 3. 使用 TailwindCSS + dark: 前缀支持深色模式
# 4. 使用 TypeScript 类型注解

示例组件模板:

vue
<template>
  <div class="bg-white dark:bg-slate-900 rounded-lg p-4">
    <h3 class="text-lg font-semibold text-slate-900 dark:text-white">
      {{ title }}
    </h3>
    <button
      @click="handleClick"
      class="mt-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 dark:bg-indigo-500 dark:hover:bg-indigo-600 text-white rounded"
    >
      Action
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

interface Props {
  title: string
}

const props = withDefaults(defineProps<Props>(), {
  title: 'Default Title'
})

const emit = defineEmits<{
  click: []
}>()

const handleClick = () => {
  emit('click')
}
</script>

<style scoped>
/* 如需局部样式 */
</style>

修改页面布局

  1. frontend/src/pages/ 找到对应页面
  2. 修改模板、脚本或样式
  3. 测试响应式设计和深色模式
  4. 运行 pnpm dev 本地预览

新增状态管理

frontend/src/stores/ 创建新的 store:

typescript
// myFeature.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useMyFeatureStore = defineStore('myFeature', () => {
  const items = ref([])
  
  const itemCount = computed(() => items.value.length)
  
  const addItem = (item: any) => {
    items.value.push(item)
  }
  
  return { items, itemCount, addItem }
})

在组件中使用:

typescript
import { useMyFeatureStore } from '../stores/myFeature'

const store = useMyFeatureStore()

后端任务

添加新的 API 端点

  1. supabase/functions/ 创建新函数
  2. 实现请求处理
  3. 添加错误处理和日志
  4. 部署并测试

修改数据库架构

bash
# 1. 创建新迁移
supabase migration new add_new_column

# 2. 编写 SQL(在 supabase/migrations/timestamp_add_new_column.sql)
ALTER TABLE todos ADD COLUMN new_field TEXT;

# 3. 本地测试
supabase db reset

# 4. 推送到远程
supabase db push

调用大模型 API

在 Edge Function 中调用 AI:

typescript
// 示例:调用 OpenAI
const AIResponse = await fetch(
  'https://api.openai.com/v1/chat/completions',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${Deno.env.get('OPENAI_API_KEY')}`
    },
    body: JSON.stringify({
      model: 'gpt-4',
      messages: [{ role: 'user', content: userQuery }],
      temperature: 0.7
    })
  }
);

const data = await AIResponse.json();
return data.choices[0].message.content;

测试指南

前端单元测试

使用 Vitest 编写测试:

typescript
// todoList.test.ts
import { describe, it, expect, beforeEach } from 'vitest'
import { ref } from 'vue'
import { createTodoOptimisticActions } from './todos.optimistic'

describe('TodoList', () => {
  let todosRef

  beforeEach(() => {
    todosRef = ref([])
  })

  it('should add todo', () => {
    // 测试逻辑
  })
})

运行测试:

bash
pnpm test           # 运行一次
pnpm test:watch    # 监视模式

本地手动测试

bash
# 1. 启动完整环境
supabase start
cd frontend && pnpm dev

# 2. 打开浏览器
# http://localhost:5173

# 3. 登录并测试功能
# 检查:UI 是否正确、数据是否同步、错误处理

# 4. 打开开发者工具
# 检查:网络请求、控制台错误、性能

Edge Function 测试

bash
# 1. 启动 Edge Functions
supabase functions serve

# 2. 测试请求
curl -X POST http://localhost:54321/functions/v1/breakdown_task \
  -H "Content-Type: application/json" \
  -d '{
    "query":"分解这个任务",
    "todosTree":[{"id":1,"title":"任务"}]
  }'

# 3. 查看日志
supabase logs --local

调试技巧

前端调试

使用 Vue DevTools

VS Code 扩展推荐:

  • Vue Language Features (Volar):Vue 3 语言支持
  • Debugger for Chrome:断点调试

控制台调试

javascript
// 在浏览器控制台
// 访问 Pinia Store
const { useMyStore } = await import('./stores/myStore.js')
const store = useMyStore()
console.log(store.items)

// 修改状态
store.addItem({ name: 'test' })

检查网络请求

使用浏览器开发者工具 Network 标签:

  • 检查请求 URL、方法、Headers
  • 查看响应状态和数据
  • 检查是否有 CORS 错误

后端调试

Edge Function 日志

bash
# 查看实时日志
supabase logs --local --function-name breakdown_task

# 或在函数中输出
console.log('Debug info:', value);
console.error('Error:', error);

数据库查询调试

连接本地数据库直接查询:

bash
psql postgresql://postgres:postgres@localhost:54321/postgres

# 查询例子
SELECT * FROM todos WHERE user_id = '...';
SELECT * FROM todos ORDER BY created_at DESC LIMIT 10;

代码风格与规范

前端代码风格

typescript
// ✅ 好:使用 Composition API
<script setup lang="ts">
import { ref, computed } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)

const increment = () => count.value++
</script>

// ❌ 避免:使用 Options API
export default {
  data() {
    return { count: 0 }
  },
  methods: {
    increment() { this.count++ }
  }
}

命名规范

typescript
// 文件
- components/ 下使用 PascalCase:MyComponent.vue
- stores/ 下使用 camelCase:myStore.ts
- pages/ 下使用 PascalCase:HomePage.vue

// 变量
- const myVariable = 'value'  // 常量和变量用 camelCase
- const MY_CONSTANT = 100     // 常量全大写(可选)
- type MyType = { ... }       // 类型用 PascalCase

样式规范

vue
<!-- ✅ 好:使用 TailwindCSS 类 + dark: 前缀 -->
<div class="bg-white dark:bg-slate-900 text-slate-900 dark:text-white">

<!-- ❌ 避免:自定义 CSS 除非必要 -->
<div style="background: white">

常见问题排查

问题:前端请求后端失败

bash
# 1. 检查 CORS 设置
# supabase/functions/_shared/cors.ts 是否正确配置

# 2. 检查 Edge Function 是否在运行
supabase functions serve

# 3. 检查环境变量
# .env.local 中 VITE_SUPABASE_URL 是否正确

# 4. 查看浏览器控制台错误消息

问题:数据库权限错误

bash
# 1. 检查 RLS 策略
# 确保当前用户有读写权限

# 2. 检查认证令牌
# JWT token 是否有效

# 3. 临时关闭 RLS 调试
ALTER TABLE todos DISABLE ROW LEVEL SECURITY;

# 4. 重新启用并修复策略
ALTER TABLE todos ENABLE ROW LEVEL SECURITY;

问题:AI 调用失败

bash
# 1. 检查 API 密钥
supabase secrets list

# 2. 查看 Edge Function 日志
supabase logs --local

# 3. 检查 API 配额和限制

# 4. 验证请求格式是否正确

性能优化建议

前端优化

  • 使用虚拟滚动处理大列表
  • 代码分割:按路由分割 JavaScript
  • 图片优化:使用 WebP、懒加载
  • 缓存策略:合理设置 HTTP 缓存头

后端优化

  • 查询优化:使用数据库索引
  • 批量操作:减少往返次数
  • 连接复用:使用连接池
  • 超时设置:防止长时间运行

数据库优化

  • 定期分析查询性能
  • 创建适当的索引
  • 清理过期数据
  • 考虑分区大表

部署流程

前端部署

bash
# 1. 构建生产版本
cd frontend
pnpm build

# 2. 输出在 dist/ 目录
# 3. 部署到托管服务(GitHub Pages、Vercel、Netlify)

# 示例:GitHub Pages
git add dist/
git commit -m "build: production build"
git push

后端部署

bash
# 1. 部署 Edge Function
supabase functions deploy breakdown_task

# 2. 部署数据库迁移
supabase db push

# 3. 验证部署
supabase status

获取帮助

文档使用 VuePress 构建