senior-fullstack

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Senior 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

操作步骤

  1. Design database schema with Prisma
  2. Define relationships and indexes
  3. Create seed data for development
  4. Set up migrations workflow
  5. Implement repository pattern for data access
  1. 使用 Prisma 设计数据库 schema
  2. 定义关系和索引
  3. 创建开发用的种子数据
  4. 配置迁移工作流
  5. 实现用于数据访问的仓储模式

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 PatternIndex TypeExample
Lookup by unique fieldUnique index
@@unique([email])
Filter by foreign keyStandard index
@@index([authorId])
Filter + sort combinationComposite index
@@index([published, createdAt])
Full-text searchFull-text indexDatabase-specific
Geospatial querySpatial indexDatabase-specific
查询模式索引类型示例
按唯一字段查询唯一索引
@@unique([email])
按外键过滤普通索引
@@index([authorId])
过滤+排序组合联合索引
@@index([published, createdAt])
全文搜索全文索引数据库专属实现
地理空间查询空间索引数据库专属实现

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

操作步骤

  1. Define tRPC routers and procedures
  2. Implement input validation with Zod
  3. Add authentication middleware
  4. Build business logic in service layer
  5. Add error handling and logging
  1. 定义 tRPC 路由和 procedure
  2. 使用 Zod 实现输入参数校验
  3. 添加鉴权中间件
  4. 在服务层实现业务逻辑
  5. 添加错误处理和日志

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

鉴权模式决策表

PatternUse WhenExample
Role-based (RBAC)Simple permission modelAdmin vs User
Resource-levelOwner-only accessUser can edit own posts
Attribute-based (ABAC)Complex rulesOrg membership + role + resource state
Feature flagsGradual rolloutPremium 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

操作步骤

  1. Build pages with Server Components (default)
  2. Add Client Components for interactivity
  3. Connect to API via tRPC hooks
  4. Implement optimistic updates
  5. Add loading and error states
  1. 默认使用服务端组件构建页面
  2. 交互场景使用客户端组件实现
  3. 通过 tRPC hooks 连接 API
  4. 实现乐观更新
  5. 添加加载和错误状态

Component Type Decision Table

组件类型决策表

NeedComponent TypeData Source
Static content, data displayServer ComponentDirect DB/API call
Interactive formClient ComponenttRPC mutation hook
Real-time updatesClient ComponenttRPC subscription or polling
Search/filterClient ComponenttRPC query with debounce
Navigation chromeServer ComponentSession 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

操作步骤

  1. Set up authentication (NextAuth.js / Clerk / Lucia)
  2. Configure deployment (Vercel / Docker)
  3. Add monitoring and error tracking
  4. Implement CI/CD pipeline
  5. Performance audit
  1. 配置鉴权(NextAuth.js / Clerk / Lucia)
  2. 配置部署方案(Vercel / Docker)
  3. 添加监控和错误追踪
  4. 实现 CI/CD 流水线
  5. 性能审计

Auth Solution Decision Table

鉴权方案决策表

SolutionBest ForSSR SupportSelf-Hosted
NextAuth.js (Auth.js)OAuth providers, JWT/sessionYesYes
ClerkFast setup, managed serviceYesNo
LuciaCustom, lightweightYesYes
Supabase AuthSupabase ecosystemYesPartial
方案最佳适用场景支持 SSR支持自托管
NextAuth.js (Auth.js)OAuth 登录、JWT/会话管理
Clerk快速搭建、托管服务
Lucia自定义、轻量需求
Supabase AuthSupabase 生态项目部分支持

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 --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm prisma generate
RUN pnpm build

FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /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 --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm prisma generate
RUN pnpm build

FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /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         queries

Prisma 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-PatternWhy It Is WrongCorrect Approach
Raw SQL in componentsBypasses type safety and securityUse Prisma through tRPC
Client-side fetch when Server Components workUnnecessary JavaScript, slowerServer Components for static data
Sharing Prisma client with frontendSecurity breach, exposes DBPrisma only in server code
Missing indexes on foreign keysSlow joins and lookupsIndex every foreign key
Storing tokens in localStorageXSS vulnerabilityHttpOnly cookies
Skipping Zod validationRuntime type errorsValidate all inputs at API boundary
Monolithic tRPC routerHard to maintain, merge conflictsSplit by domain (user, post, etc.)
Business logic in tRPC proceduresHard to test, not reusableExtract 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
mcp__context7__resolve-library-id
then
mcp__context7__query-docs
for up-to-date docs. Returned docs override memorized knowledge.
  • react
    — for component patterns, hooks, or React 19+ features
  • next.js
    — for App Router, API routes, or server components
  • prisma
    — for schema design, client queries, or migrations
  • tailwindcss
    — for utility-first CSS patterns or configuration

先调用
mcp__context7__resolve-library-id
再调用
mcp__context7__query-docs
获取最新文档,返回的文档优先级高于记忆中的知识。
  • react
    — 查询组件模式、hooks 或 React 19+ 新特性
  • next.js
    — 查询 App Router、API 路由或服务端组件相关内容
  • prisma
    — 查询 schema 设计、client 查询或迁移相关内容
  • tailwindcss
    — 查询工具类 CSS 模式或配置相关内容

Integration Points

集成点

SkillRelationship
senior-frontend
UI layer follows frontend patterns
senior-backend
API layer follows backend patterns
senior-architect
Architecture decisions guide service boundaries
security-review
Auth implementation follows security patterns
testing-strategy
Full-stack testing uses strategy frameworks
code-review
Review covers all layers of the stack
performance-optimization
Optimization applies to all layers

技能关联关系
senior-frontend
UI 层遵循前端开发规范
senior-backend
API 层遵循后端开发规范
senior-architect
架构决策指导服务边界划分
security-review
鉴权实现遵循安全规范
testing-strategy
全栈测试使用对应策略框架
code-review
代码评审覆盖全栈所有层级
performance-optimization
优化覆盖全栈所有层级

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 变更必须使用迁移。