senior-fullstack
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSenior Fullstack Engineer
高级全栈工程师
Overview
概述
Deliver complete, end-to-end TypeScript applications covering database design, API layer, frontend UI, authentication, and deployment. This skill specializes in the modern TypeScript full-stack: Next.js App Router, tRPC for type-safe APIs, Prisma for database access, and production deployment with monitoring.
Announce at start: "I'm using the senior-fullstack skill for end-to-end TypeScript development."
交付覆盖数据库设计、API 层、前端 UI、鉴权和部署的完整端到端 TypeScript 应用。本技能专注于现代 TypeScript 全栈技术栈:Next.js App Router、用于实现类型安全 API 的 tRPC、用于数据库访问的 Prisma,以及带监控的生产环境部署。
开篇声明: "我将使用 senior-fullstack 技能完成端到端 TypeScript 开发。"
Phase 1: Data Layer
阶段1:数据层
Goal: Design the database schema and data access patterns.
目标: 设计数据库 schema 和数据访问模式。
Actions
操作步骤
- Design database schema with Prisma
- Define relationships and indexes
- Create seed data for development
- Set up migrations workflow
- Implement repository pattern for data access
- 使用 Prisma 设计数据库 schema
- 定义关系和索引
- 创建开发用的种子数据
- 配置迁移工作流
- 实现用于数据访问的仓储模式
Prisma Schema Example
Prisma Schema 示例
prisma
model User {
id String @id @default(cuid())
email String @unique
name String
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([email])
@@index([createdAt])
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([authorId])
@@index([published, createdAt])
}prisma
model User {
id String @id @default(cuid())
email String @unique
name String
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([email])
@@index([createdAt])
}
model Post {
id String @id @default(cuid())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([authorId])
@@index([published, createdAt])
}Index Strategy Decision Table
索引策略决策表
| Query Pattern | Index Type | Example |
|---|---|---|
| Lookup by unique field | Unique index | |
| Filter by foreign key | Standard index | |
| Filter + sort combination | Composite index | |
| Full-text search | Full-text index | Database-specific |
| Geospatial query | Spatial index | Database-specific |
| 查询模式 | 索引类型 | 示例 |
|---|---|---|
| 按唯一字段查询 | 唯一索引 | |
| 按外键过滤 | 普通索引 | |
| 过滤+排序组合 | 联合索引 | |
| 全文搜索 | 全文索引 | 数据库专属实现 |
| 地理空间查询 | 空间索引 | 数据库专属实现 |
STOP — Do NOT proceed to Phase 2 until:
停止——满足以下条件前不要进入阶段2:
- Schema is defined with all relationships
- Indexes cover all query patterns
- Seed data script exists
- Migrations are generated and tested
- Schema 已定义所有关联关系
- 索引覆盖了所有查询模式
- 种子数据脚本已就绪
- 迁移已生成并完成测试
Phase 2: API Layer
阶段2:API 层
Goal: Build type-safe API with tRPC and Zod validation.
目标: 使用 tRPC 和 Zod 校验构建类型安全的 API。
Actions
操作步骤
- Define tRPC routers and procedures
- Implement input validation with Zod
- Add authentication middleware
- Build business logic in service layer
- Add error handling and logging
- 定义 tRPC 路由和 procedure
- 使用 Zod 实现输入参数校验
- 添加鉴权中间件
- 在服务层实现业务逻辑
- 添加错误处理和日志
tRPC Router Example
tRPC 路由示例
typescript
export const userRouter = router({
list: protectedProcedure
.input(z.object({
page: z.number().min(1).default(1),
pageSize: z.number().min(1).max(100).default(20),
search: z.string().optional(),
}))
.query(async ({ ctx, input }) => {
const { page, pageSize, search } = input;
const where = search ? { name: { contains: search, mode: 'insensitive' } } : {};
const [users, total] = await Promise.all([
ctx.db.user.findMany({
where, skip: (page - 1) * pageSize, take: pageSize, orderBy: { createdAt: 'desc' },
}),
ctx.db.user.count({ where }),
]);
return { users, total, totalPages: Math.ceil(total / pageSize) };
}),
create: protectedProcedure
.input(createUserSchema)
.mutation(async ({ ctx, input }) => {
return ctx.db.user.create({ data: input });
}),
});typescript
export const userRouter = router({
list: protectedProcedure
.input(z.object({
page: z.number().min(1).default(1),
pageSize: z.number().min(1).max(100).default(20),
search: z.string().optional(),
}))
.query(async ({ ctx, input }) => {
const { page, pageSize, search } = input;
const where = search ? { name: { contains: search, mode: 'insensitive' } } : {};
const [users, total] = await Promise.all([
ctx.db.user.findMany({
where, skip: (page - 1) * pageSize, take: pageSize, orderBy: { createdAt: 'desc' },
}),
ctx.db.user.count({ where }),
]);
return { users, total, totalPages: Math.ceil(total / pageSize) };
}),
create: protectedProcedure
.input(createUserSchema)
.mutation(async ({ ctx, input }) => {
return ctx.db.user.create({ data: input });
}),
});Authorization Pattern Decision Table
鉴权模式决策表
| Pattern | Use When | Example |
|---|---|---|
| Role-based (RBAC) | Simple permission model | Admin vs User |
| Resource-level | Owner-only access | User can edit own posts |
| Attribute-based (ABAC) | Complex rules | Org membership + role + resource state |
| Feature flags | Gradual rollout | Premium features |
| 模式 | 适用场景 | 示例 |
|---|---|---|
| 基于角色的鉴权(RBAC) | 简单权限模型 | 管理员 vs 普通用户 |
| 资源级鉴权 | 仅所有者可访问 | 用户仅可编辑自己发布的帖子 |
| 基于属性的鉴权(ABAC) | 复杂规则场景 | 组织成员身份 + 角色 + 资源状态 |
| 功能开关 | 灰度发布 | 高级付费功能 |
STOP — Do NOT proceed to Phase 3 until:
停止——满足以下条件前不要进入阶段3:
- All tRPC routers are defined with Zod validation
- Auth middleware protects appropriate routes
- Business logic is in service layer (not in router)
- Error handling returns structured errors
- 所有 tRPC 路由都配置了 Zod 校验
- 鉴权中间件已保护对应路由
- 业务逻辑存放在服务层(而非路由中)
- 错误处理返回结构化错误信息
Phase 3: UI Layer
阶段3:UI 层
Goal: Build pages with Server Components by default, Client Components for interactivity.
目标: 默认使用服务端组件构建页面,交互场景使用客户端组件。
Actions
操作步骤
- Build pages with Server Components (default)
- Add Client Components for interactivity
- Connect to API via tRPC hooks
- Implement optimistic updates
- Add loading and error states
- 默认使用服务端组件构建页面
- 交互场景使用客户端组件实现
- 通过 tRPC hooks 连接 API
- 实现乐观更新
- 添加加载和错误状态
Component Type Decision Table
组件类型决策表
| Need | Component Type | Data Source |
|---|---|---|
| Static content, data display | Server Component | Direct DB/API call |
| Interactive form | Client Component | tRPC mutation hook |
| Real-time updates | Client Component | tRPC subscription or polling |
| Search/filter | Client Component | tRPC query with debounce |
| Navigation chrome | Server Component | Session data |
| 需求 | 组件类型 | 数据源 |
|---|---|---|
| 静态内容、数据展示 | 服务端组件 | 直接调用数据库/API |
| 交互表单 | 客户端组件 | tRPC mutation hook |
| 实时更新 | 客户端组件 | tRPC 订阅或轮询 |
| 搜索/过滤 | 客户端组件 | 带防抖的 tRPC query |
| 导航栏 | 服务端组件 | 会话数据 |
STOP — Do NOT proceed to Phase 4 until:
停止——满足以下条件前不要进入阶段4:
- Pages use Server Components by default
- Client Components are minimal and justified
- Loading and error states exist for all data-fetching paths
- Optimistic updates work for mutations
- 页面默认使用服务端组件
- 客户端组件最小化且有合理的使用理由
- 所有数据获取路径都配置了加载和错误状态
- mutation 已实现乐观更新
Phase 4: Production
阶段4:生产部署
Goal: Prepare for deployment with auth, monitoring, and CI/CD.
目标: 完成鉴权、监控和 CI/CD 配置,准备上线。
Actions
操作步骤
- Set up authentication (NextAuth.js / Clerk / Lucia)
- Configure deployment (Vercel / Docker)
- Add monitoring and error tracking
- Implement CI/CD pipeline
- Performance audit
- 配置鉴权(NextAuth.js / Clerk / Lucia)
- 配置部署方案(Vercel / Docker)
- 添加监控和错误追踪
- 实现 CI/CD 流水线
- 性能审计
Auth Solution Decision Table
鉴权方案决策表
| Solution | Best For | SSR Support | Self-Hosted |
|---|---|---|---|
| NextAuth.js (Auth.js) | OAuth providers, JWT/session | Yes | Yes |
| Clerk | Fast setup, managed service | Yes | No |
| Lucia | Custom, lightweight | Yes | Yes |
| Supabase Auth | Supabase ecosystem | Yes | Partial |
| 方案 | 最佳适用场景 | 支持 SSR | 支持自托管 |
|---|---|---|---|
| NextAuth.js (Auth.js) | OAuth 登录、JWT/会话管理 | 是 | 是 |
| Clerk | 快速搭建、托管服务 | 是 | 否 |
| Lucia | 自定义、轻量需求 | 是 | 是 |
| Supabase Auth | Supabase 生态项目 | 是 | 部分支持 |
Monitoring Checklist
监控检查清单
- Error tracking (Sentry) with source maps
- Performance monitoring (Vercel Analytics or custom)
- Database query performance (Prisma metrics)
- API endpoint latency and error rates
- Uptime monitoring (external ping)
- Log aggregation with structured logging
- Alerting for error rate spikes
- 错误追踪(Sentry)配置了 source map
- 性能监控(Vercel Analytics 或自定义方案)
- 数据库查询性能监控(Prisma metrics)
- API 端点延迟和错误率监控
- 正常运行时间监控(外部 ping 服务)
- 结构化日志聚合
- 错误率突增告警配置
Docker Deployment
Docker 部署配置
dockerfile
FROM node:20-alpine AS base
RUN corepack enable
FROM base AS deps
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
FROM base AS builder
WORKDIR /app
COPY /app/node_modules ./node_modules
COPY . .
RUN pnpm prisma generate
RUN pnpm build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY /app/.next/standalone ./
COPY /app/.next/static ./.next/static
COPY /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]dockerfile
FROM node:20-alpine AS base
RUN corepack enable
FROM base AS deps
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
FROM base AS builder
WORKDIR /app
COPY /app/node_modules ./node_modules
COPY . .
RUN pnpm prisma generate
RUN pnpm build
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY /app/.next/standalone ./
COPY /app/.next/static ./.next/static
COPY /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]STOP — Production ready when:
停止——满足以下条件即为生产就绪:
- Auth is configured and tested
- Deployment pipeline works (preview + production)
- Monitoring and alerting are active
- Performance audit completed
- 鉴权已配置并完成测试
- 部署流水线正常运行(预览环境+生产环境)
- 监控和告警已生效
- 性能审计已完成
Full-Stack Type Safety Pipeline
全栈类型安全链路
Prisma Schema -> Prisma Client (types) -> tRPC Router -> tRPC Hooks -> React Components
| | | | |
Migration Type-safe DB Validated API Auto-typed Rendered UI
queries with Zod queriesPrisma Schema -> Prisma Client (types) -> tRPC Router -> tRPC Hooks -> React Components
| | | | |
迁移操作 类型安全的数据库 Zod 校验的API 自动类型推导的 渲染后的UI
查询操作 接口 查询Project Structure
项目结构
prisma/
schema.prisma
migrations/
seed.ts
src/
app/ # Next.js App Router
(auth)/ # Auth route group
(dashboard)/ # Protected route group
api/trpc/[trpc]/ # tRPC handler
server/
db.ts # Prisma client singleton
trpc.ts # tRPC init
routers/ # tRPC routers
services/ # Business logic
components/
ui/ # Design system atoms
features/ # Feature components
hooks/ # Custom React hooks
lib/
trpc.ts # tRPC client
auth.ts # Auth configuration
validators.ts # Zod schemas
tests/
unit/
integration/
e2e/prisma/
schema.prisma
migrations/
seed.ts
src/
app/ # Next.js App Router
(auth)/ # 鉴权路由组
(dashboard)/ # 受保护路由组
api/trpc/[trpc]/ # tRPC 处理器
server/
db.ts # Prisma client 单例
trpc.ts # tRPC 初始化
routers/ # tRPC 路由
services/ # 业务逻辑
components/
ui/ # 设计系统原子组件
features/ # 业务功能组件
hooks/ # 自定义 React hooks
lib/
trpc.ts # tRPC 客户端
auth.ts # 鉴权配置
validators.ts # Zod schema
tests/
unit/
integration/
e2e/Anti-Patterns / Common Mistakes
反模式/常见错误
| Anti-Pattern | Why It Is Wrong | Correct Approach |
|---|---|---|
| Raw SQL in components | Bypasses type safety and security | Use Prisma through tRPC |
| Client-side fetch when Server Components work | Unnecessary JavaScript, slower | Server Components for static data |
| Sharing Prisma client with frontend | Security breach, exposes DB | Prisma only in server code |
| Missing indexes on foreign keys | Slow joins and lookups | Index every foreign key |
| Storing tokens in localStorage | XSS vulnerability | HttpOnly cookies |
| Skipping Zod validation | Runtime type errors | Validate all inputs at API boundary |
| Monolithic tRPC router | Hard to maintain, merge conflicts | Split by domain (user, post, etc.) |
| Business logic in tRPC procedures | Hard to test, not reusable | Extract to service layer |
| 反模式 | 问题原因 | 正确做法 |
|---|---|---|
| 在组件中写原生 SQL | 绕过类型安全和安全校验 | 通过 tRPC 调用 Prisma |
| 可使用服务端组件的场景使用客户端 fetch | 产生不必要的 JavaScript 代码,性能更差 | 静态数据使用服务端组件渲染 |
| 向前端暴露 Prisma client | 存在安全漏洞,暴露数据库结构 | Prisma 仅在服务端代码中使用 |
| 外键缺失索引 | 关联查询和查询速度慢 | 所有外键都添加索引 |
| 将 token 存储在 localStorage | 存在 XSS 漏洞 | 使用 HttpOnly cookie |
| 省略 Zod 校验 | 出现运行时类型错误 | 在 API 边界校验所有输入参数 |
| 单体 tRPC 路由 | 难以维护,容易出现合并冲突 | 按领域拆分路由(用户、帖子等) |
| 业务逻辑写在 tRPC procedure 中 | 难以测试,复用性差 | 抽离到服务层 |
Documentation Lookup (Context7)
文档查询(Context7)
Use then for up-to-date docs. Returned docs override memorized knowledge.
mcp__context7__resolve-library-idmcp__context7__query-docs- — for component patterns, hooks, or React 19+ features
react - — for App Router, API routes, or server components
next.js - — for schema design, client queries, or migrations
prisma - — for utility-first CSS patterns or configuration
tailwindcss
先调用 再调用 获取最新文档,返回的文档优先级高于记忆中的知识。
mcp__context7__resolve-library-idmcp__context7__query-docs- — 查询组件模式、hooks 或 React 19+ 新特性
react - — 查询 App Router、API 路由或服务端组件相关内容
next.js - — 查询 schema 设计、client 查询或迁移相关内容
prisma - — 查询工具类 CSS 模式或配置相关内容
tailwindcss
Integration Points
集成点
| Skill | Relationship |
|---|---|
| UI layer follows frontend patterns |
| API layer follows backend patterns |
| Architecture decisions guide service boundaries |
| Auth implementation follows security patterns |
| Full-stack testing uses strategy frameworks |
| Review covers all layers of the stack |
| Optimization applies to all layers |
| 技能 | 关联关系 |
|---|---|
| UI 层遵循前端开发规范 |
| API 层遵循后端开发规范 |
| 架构决策指导服务边界划分 |
| 鉴权实现遵循安全规范 |
| 全栈测试使用对应策略框架 |
| 代码评审覆盖全栈所有层级 |
| 优化覆盖全栈所有层级 |
Key Principles
核心原则
- Single language (TypeScript) from database to browser
- Type safety across the entire stack (no runtime type mismatches)
- Server Components by default, Client Components by necessity
- Validate all inputs at the API boundary with Zod
- Database indexes for every query pattern
- Environment-based configuration (no hard-coded values)
- 从数据库到浏览器统一使用 TypeScript 作为开发语言
- 全栈链路类型安全(无运行时类型不匹配问题)
- 默认使用服务端组件,仅必要时使用客户端组件
- 使用 Zod 在 API 边界校验所有输入参数
- 所有查询模式都配置对应的数据库索引
- 基于环境变量配置(无硬编码值)
Skill Type
技能类型
FLEXIBLE — Adapt the tech choices to the project context. The four-phase process is strongly recommended. Type safety across the stack is non-negotiable. All API inputs must be validated with Zod. Database schema changes must use migrations.
灵活适配 — 可根据项目上下文调整技术选型。强烈建议遵循四阶段流程。全栈类型安全是硬性要求。所有 API 输入必须使用 Zod 校验。数据库 schema 变更必须使用迁移。