senior-fullstack

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Senior Full-Stack Developer

资深全栈开发工程师

Expert-level full-stack development for modern web applications.
为现代Web应用提供专家级全栈开发指导。

Core Competencies

核心能力

  • Frontend frameworks (React, Vue, Next.js)
  • Backend services (Node.js, Python, Go)
  • Database design (SQL, NoSQL)
  • API development (REST, GraphQL)
  • Authentication and authorization
  • Performance optimization
  • Testing strategies
  • Deployment and DevOps
  • 前端框架(React、Vue、Next.js)
  • 后端服务(Node.js、Python、Go)
  • 数据库设计(SQL、NoSQL)
  • API开发(REST、GraphQL)
  • 身份验证与授权
  • 性能优化
  • 测试策略
  • 部署与DevOps

Tech Stack Recommendations

技术栈推荐

Modern Full-Stack (2024+)

2024+现代全栈技术栈

Frontend:
  • Framework: Next.js 14+ (App Router)
  • Styling: Tailwind CSS
  • State: Zustand or Jotai
  • Forms: React Hook Form + Zod
  • Data Fetching: TanStack Query
Backend:
  • Runtime: Node.js or Bun
  • Framework: Next.js API Routes or Hono
  • ORM: Prisma or Drizzle
  • Validation: Zod
Database:
  • Primary: PostgreSQL
  • Cache: Redis
  • Search: Elasticsearch or Typesense
Infrastructure:
  • Hosting: Vercel, Railway, or AWS
  • CDN: Cloudflare
  • Storage: S3-compatible
前端:
  • 框架:Next.js 14+(App Router)
  • 样式:Tailwind CSS
  • 状态管理:Zustand或Jotai
  • 表单:React Hook Form + Zod
  • 数据获取:TanStack Query
后端:
  • 运行时:Node.js或Bun
  • 框架:Next.js API Routes或Hono
  • ORM:Prisma或Drizzle
  • 验证:Zod
数据库:
  • 主数据库:PostgreSQL
  • 缓存:Redis
  • 搜索:Elasticsearch或Typesense
基础设施:
  • 托管:Vercel、Railway或AWS
  • CDN:Cloudflare
  • 存储:兼容S3的服务

Project Structure

项目结构

Next.js App Router Structure

Next.js App Router结构

project/
├── src/
│   ├── app/
│   │   ├── (auth)/
│   │   │   ├── login/
│   │   │   └── register/
│   │   ├── (dashboard)/
│   │   │   ├── layout.tsx
│   │   │   └── page.tsx
│   │   ├── api/
│   │   │   └── [...route]/
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── components/
│   │   ├── ui/
│   │   └── features/
│   ├── lib/
│   │   ├── db.ts
│   │   ├── auth.ts
│   │   └── utils.ts
│   ├── hooks/
│   ├── types/
│   └── styles/
├── prisma/
│   └── schema.prisma
├── public/
├── tests/
└── config files
project/
├── src/
│   ├── app/
│   │   ├── (auth)/
│   │   │   ├── login/
│   │   │   └── register/
│   │   ├── (dashboard)/
│   │   │   ├── layout.tsx
│   │   │   └── page.tsx
│   │   ├── api/
│   │   │   └── [...route]/
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── components/
│   │   ├── ui/
│   │   └── features/
│   ├── lib/
│   │   ├── db.ts
│   │   ├── auth.ts
│   │   └── utils.ts
│   ├── hooks/
│   ├── types/
│   └── styles/
├── prisma/
│   └── schema.prisma
├── public/
├── tests/
└── config files

Frontend Patterns

前端模式

Component Architecture

组件架构

Atomic Design:
components/
├── atoms/        # Button, Input, Label
├── molecules/    # FormField, SearchBar
├── organisms/    # Header, ProductCard
├── templates/    # PageLayout, DashboardLayout
└── pages/        # Assembled pages
Feature-Based:
features/
├── auth/
│   ├── components/
│   ├── hooks/
│   ├── api/
│   └── types/
├── products/
│   ├── components/
│   ├── hooks/
│   ├── api/
│   └── types/
原子设计:
components/
├── atoms/        # 按钮、输入框、标签
├── molecules/    # 表单项、搜索栏
├── organisms/    # 头部、产品卡片
├── templates/    # 页面布局、仪表盘布局
└── pages/        # 组装好的页面
基于功能的架构:
features/
├── auth/
│   ├── components/
│   ├── hooks/
│   ├── api/
│   └── types/
├── products/
│   ├── components/
│   ├── hooks/
│   ├── api/
│   └── types/

React Patterns

React模式

Custom Hook Pattern:
typescript
function useUser(userId: string) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUser(userId),
    staleTime: 5 * 60 * 1000,
  });

  return { user: data, isLoading, error };
}
Compound Component Pattern:
typescript
const Card = ({ children }: Props) => (
  <div className="card">{children}</div>
);
Card.Header = ({ children }: Props) => (
  <div className="card-header">{children}</div>
);
Card.Body = ({ children }: Props) => (
  <div className="card-body">{children}</div>
);
Card.Footer = ({ children }: Props) => (
  <div className="card-footer">{children}</div>
);

// Usage
<Card>
  <Card.Header>Title</Card.Header>
  <Card.Body>Content</Card.Body>
</Card>
自定义Hook模式:
typescript
function useUser(userId: string) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUser(userId),
    staleTime: 5 * 60 * 1000,
  });

  return { user: data, isLoading, error };
}
复合组件模式:
typescript
const Card = ({ children }: Props) => (
  <div className="card">{children}</div>
);
Card.Header = ({ children }: Props) => (
  <div className="card-header">{children}</div>
);
Card.Body = ({ children }: Props) => (
  <div className="card-body">{children}</div>
);
Card.Footer = ({ children }: Props) => (
  <div className="card-footer">{children}</div>
);

// 用法
<Card>
  <Card.Header>Title</Card.Header>
  <Card.Body>Content</Card.Body>
</Card>

State Management

状态管理

Zustand Store:
typescript
interface Store {
  user: User | null;
  setUser: (user: User) => void;
  logout: () => void;
}

const useStore = create<Store>((set) => ({
  user: null,
  setUser: (user) => set({ user }),
  logout: () => set({ user: null }),
}));
Zustand Store:
typescript
interface Store {
  user: User | null;
  setUser: (user: User) => void;
  logout: () => void;
}

const useStore = create<Store>((set) => ({
  user: null,
  setUser: (user) => set({ user }),
  logout: () => set({ user: null }),
}));

Backend Patterns

后端模式

API Design

API设计

RESTful Endpoints:
GET    /api/users          # List users
POST   /api/users          # Create user
GET    /api/users/:id      # Get user
PUT    /api/users/:id      # Update user
DELETE /api/users/:id      # Delete user
GET    /api/users/:id/posts # User's posts
Response Format:
typescript
// Success
{
  "data": { ... },
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 100
  }
}

// Error
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}
RESTful端点:
GET    /api/users          # 列出用户
POST   /api/users          # 创建用户
GET    /api/users/:id      # 获取单个用户
PUT    /api/users/:id      # 更新用户
DELETE /api/users/:id      # 删除用户
GET    /api/users/:id/posts # 用户的文章
响应格式:
typescript
// 成功
{
  "data": { ... },
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 100
  }
}

// 错误
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}

Request Validation

请求验证

typescript
import { z } from 'zod';

const CreateUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(100),
  role: z.enum(['user', 'admin']).default('user'),
});

async function createUser(req: Request) {
  const body = await req.json();
  const result = CreateUserSchema.safeParse(body);

  if (!result.success) {
    return Response.json(
      { error: { code: 'VALIDATION_ERROR', details: result.error.issues } },
      { status: 400 }
    );
  }

  const user = await db.user.create({ data: result.data });
  return Response.json({ data: user }, { status: 201 });
}
typescript
import { z } from 'zod';

const CreateUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(100),
  role: z.enum(['user', 'admin']).default('user'),
});

async function createUser(req: Request) {
  const body = await req.json();
  const result = CreateUserSchema.safeParse(body);

  if (!result.success) {
    return Response.json(
      { error: { code: 'VALIDATION_ERROR', details: result.error.issues } },
      { status: 400 }
    );
  }

  const user = await db.user.create({ data: result.data });
  return Response.json({ data: user }, { status: 201 });
}

Error Handling

错误处理

typescript
class AppError extends Error {
  constructor(
    public code: string,
    public message: string,
    public statusCode: number = 400,
    public details?: unknown
  ) {
    super(message);
  }
}

// Middleware
function errorHandler(error: Error) {
  if (error instanceof AppError) {
    return Response.json(
      { error: { code: error.code, message: error.message, details: error.details } },
      { status: error.statusCode }
    );
  }

  console.error(error);
  return Response.json(
    { error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' } },
    { status: 500 }
  );
}
typescript
class AppError extends Error {
  constructor(
    public code: string,
    public message: string,
    public statusCode: number = 400,
    public details?: unknown
  ) {
    super(message);
  }
}

// 中间件
function errorHandler(error: Error) {
  if (error instanceof AppError) {
    return Response.json(
      { error: { code: error.code, message: error.message, details: error.details } },
      { status: error.statusCode }
    );
  }

  console.error(error);
  return Response.json(
    { error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' } },
    { status: 500 }
  );
}

Database Patterns

数据库模式

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
}

model Post {
  id        String   @id @default(cuid())
  title     String
  content   String
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
  tags      Tag[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@index([authorId])
}

enum Role {
  USER
  ADMIN
}
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
}

model Post {
  id        String   @id @default(cuid())
  title     String
  content   String
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
  tags      Tag[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@index([authorId])
}

enum Role {
  USER
  ADMIN
}

Query Optimization

查询优化

typescript
// Bad: N+1 query
const users = await db.user.findMany();
for (const user of users) {
  const posts = await db.post.findMany({ where: { authorId: user.id } });
}

// Good: Include relation
const users = await db.user.findMany({
  include: {
    posts: {
      where: { published: true },
      take: 5,
      orderBy: { createdAt: 'desc' },
    },
  },
});

// Pagination
const posts = await db.post.findMany({
  skip: (page - 1) * limit,
  take: limit,
  where: { published: true },
  orderBy: { createdAt: 'desc' },
});
typescript
// 糟糕:N+1查询
const users = await db.user.findMany();
for (const user of users) {
  const posts = await db.post.findMany({ where: { authorId: user.id } });
}

// 良好:包含关联关系
const users = await db.user.findMany({
  include: {
    posts: {
      where: { published: true },
      take: 5,
      orderBy: { createdAt: 'desc' },
    },
  },
});

// 分页
const posts = await db.post.findMany({
  skip: (page - 1) * limit,
  take: limit,
  where: { published: true },
  orderBy: { createdAt: 'desc' },
});

Authentication

身份验证

JWT Authentication Flow

JWT身份验证流程

typescript
// Login
async function login(email: string, password: string) {
  const user = await db.user.findUnique({ where: { email } });
  if (!user || !await verifyPassword(password, user.passwordHash)) {
    throw new AppError('INVALID_CREDENTIALS', 'Invalid email or password', 401);
  }

  const token = jwt.sign(
    { userId: user.id, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: '7d' }
  );

  return { token, user: sanitizeUser(user) };
}

// Middleware
async function authenticate(req: Request) {
  const header = req.headers.get('authorization');
  if (!header?.startsWith('Bearer ')) {
    throw new AppError('UNAUTHORIZED', 'Missing token', 401);
  }

  const token = header.slice(7);
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);
    return payload;
  } catch {
    throw new AppError('UNAUTHORIZED', 'Invalid token', 401);
  }
}
typescript
// 登录
async function login(email: string, password: string) {
  const user = await db.user.findUnique({ where: { email } });
  if (!user || !await verifyPassword(password, user.passwordHash)) {
    throw new AppError('INVALID_CREDENTIALS', 'Invalid email or password', 401);
  }

  const token = jwt.sign(
    { userId: user.id, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: '7d' }
  );

  return { token, user: sanitizeUser(user) };
}

// 中间件
async function authenticate(req: Request) {
  const header = req.headers.get('authorization');
  if (!header?.startsWith('Bearer ')) {
    throw new AppError('UNAUTHORIZED', 'Missing token', 401);
  }

  const token = header.slice(7);
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);
    return payload;
  } catch {
    throw new AppError('UNAUTHORIZED', 'Invalid token', 401);
  }
}

Session-Based Auth (Next.js)

基于会话的身份验证(Next.js)

typescript
// Using NextAuth.js
import NextAuth from 'next-auth';
import { PrismaAdapter } from '@auth/prisma-adapter';

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    Credentials({
      credentials: {
        email: { type: 'email' },
        password: { type: 'password' },
      },
      authorize: async (credentials) => {
        // Validate credentials
      },
    }),
  ],
  session: { strategy: 'jwt' },
});
typescript
// 使用NextAuth.js
import NextAuth from 'next-auth';
import { PrismaAdapter } from '@auth/prisma-adapter';

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    Credentials({
      credentials: {
        email: { type: 'email' },
        password: { type: 'password' },
      },
      authorize: async (credentials) => {
        // 验证凭证
      },
    }),
  ],
  session: { strategy: 'jwt' },
});

Testing Strategy

测试策略

Testing Pyramid

测试金字塔

         /\
        /  \     E2E (Playwright)
       /----\    - Critical user flows
      /      \   - 10% of tests
     /--------\  Integration
    /          \ - API endpoints
   /------------\- 30% of tests
  /    Unit      \
 /----------------\
 - Components, Utils
 - 60% of tests
         /\
        /  \     E2E测试(Playwright)
       /----\    - 关键用户流程
      /      \   - 占测试总量的10%
     /--------\ 集成测试
    /          \ - API端点
   /------------\- 占测试总量的30%
  /    单元测试      \
 /----------------\
 - 组件、工具函数
 - 占测试总量的60%

Test Examples

测试示例

Unit Test:
typescript
describe('formatCurrency', () => {
  it('formats USD correctly', () => {
    expect(formatCurrency(1234.56, 'USD')).toBe('$1,234.56');
  });

  it('handles zero', () => {
    expect(formatCurrency(0, 'USD')).toBe('$0.00');
  });
});
API Integration Test:
typescript
describe('POST /api/users', () => {
  it('creates user with valid data', async () => {
    const response = await app.request('/api/users', {
      method: 'POST',
      body: JSON.stringify({ email: 'test@example.com', name: 'Test' }),
    });

    expect(response.status).toBe(201);
    const data = await response.json();
    expect(data.data.email).toBe('test@example.com');
  });

  it('rejects invalid email', async () => {
    const response = await app.request('/api/users', {
      method: 'POST',
      body: JSON.stringify({ email: 'invalid', name: 'Test' }),
    });

    expect(response.status).toBe(400);
  });
});
单元测试:
typescript
describe('formatCurrency', () => {
  it('正确格式化美元', () => {
    expect(formatCurrency(1234.56, 'USD')).toBe('$1,234.56');
  });

  it('处理零值', () => {
    expect(formatCurrency(0, 'USD')).toBe('$0.00');
  });
});
API集成测试:
typescript
describe('POST /api/users', () => {
  it('使用有效数据创建用户', async () => {
    const response = await app.request('/api/users', {
      method: 'POST',
      body: JSON.stringify({ email: 'test@example.com', name: 'Test' }),
    });

    expect(response.status).toBe(201);
    const data = await response.json();
    expect(data.data.email).toBe('test@example.com');
  });

  it('拒绝无效邮箱', async () => {
    const response = await app.request('/api/users', {
      method: 'POST',
      body: JSON.stringify({ email: 'invalid', name: 'Test' }),
    });

    expect(response.status).toBe(400);
  });
});

Performance Optimization

性能优化

Frontend Performance

前端性能

Code Splitting:
typescript
const Dashboard = lazy(() => import('./Dashboard'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <Dashboard />
    </Suspense>
  );
}
Image Optimization:
typescript
import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority
  placeholder="blur"
/>
代码分割:
typescript
const Dashboard = lazy(() => import('./Dashboard'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <Dashboard />
    </Suspense>
  );
}
图片优化:
typescript
import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority
  placeholder="blur"
/>

Backend Performance

后端性能

Caching:
typescript
import { Redis } from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function getUser(id: string) {
  const cached = await redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);

  const user = await db.user.findUnique({ where: { id } });
  await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);
  return user;
}
缓存:
typescript
import { Redis } from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function getUser(id: string) {
  const cached = await redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);

  const user = await db.user.findUnique({ where: { id } });
  await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);
  return user;
}

Reference Materials

参考资料

  • references/react_patterns.md
    - React best practices
  • references/api_design.md
    - API design guidelines
  • references/database_patterns.md
    - Database optimization
  • references/security_checklist.md
    - Security best practices
  • references/react_patterns.md
    - React最佳实践
  • references/api_design.md
    - API设计指南
  • references/database_patterns.md
    - 数据库优化
  • references/security_checklist.md
    - 安全最佳实践

Scripts

脚本

bash
undefined
bash
undefined

Project scaffolder

项目脚手架

python scripts/scaffold.py --name my-app --stack nextjs
python scripts/scaffold.py --name my-app --stack nextjs

Code quality analyzer

代码质量分析器

python scripts/code_quality.py --path ./src
python scripts/code_quality.py --path ./src

Database migration helper

数据库迁移助手

python scripts/db_migrate.py --action generate
python scripts/db_migrate.py --action generate

Performance audit

性能审计

python scripts/perf_audit.py --url https://localhost:3000
undefined
python scripts/perf_audit.py --url https://localhost:3000
undefined