mcpField
A
application-patterns

application-patterns

github.com/miles990开发2649 次安装40 周前更新
代码仓库

关于 application-patterns

application-patterns 是一项介绍真实应用常见开发模式的参考技能,面向应用开发者,涵盖 CRUD、身份验证、管理面板、文件处理、搜索、工作流和国际化。

主要功能

  1. 01CRUD 数据流与表单验证
  2. 02身份验证与会话策略
  3. 03管理表格与批量操作
  4. 04文件上传与图像处理
  5. 05搜索架构与功能清单
  6. 06工作流模式与国际化

适用场景

  1. 01规划从 CRUD 表单到数据库的数据流
  2. 02选择身份验证和会话方案
  3. 03设计文件上传或搜索架构
  4. 04组织审批工作流和翻译内容

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/miles990/claude-software-skills --skill application-patterns

安装后在 Claude Code 中输入/application-patterns确认已加载。

详细介绍

应用开发模式

概述

构建真实世界应用的常见模式。这些模式解决了应用开发中反复出现的问题。


CRUD 应用

数据流模式
┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────┐
│  Form   │ ──→ │Validate │ ──→ │ Service │ ──→ │   DB    │
└─────────┘     └─────────┘     └─────────┘     └─────────┘
     ↑                                               │
     └───────────── Response ←───────────────────────┘
表单处理最佳实践
// 1. Validation schema (shared frontend/backend)
const userSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(100),
  role: z.enum(['admin', 'user', 'guest'])
});

// 2. Server action with error handling
async function createUser(formData: FormData) {
  const result = userSchema.safeParse(Object.fromEntries(formData));

  if (!result.success) {
    return { error: result.error.flatten() };
  }

  try {
    const user = await db.user.create({ data: result.data });
    return { success: true, data: user };
  } catch (e) {
    if (e.code === 'P2002') {
      return { error: { email: 'Email already exists' } };
    }
    throw e;
  }
}

用户身份验证

身份验证流程
┌────────────────────────────────────────────────────────────┐
│                    Authentication Flows                     │
├────────────────────────────────────────────────────────────┤
│                                                            │
│  Email/Password:                                           │
│  Login → Validate → Create Session → Set Cookie → Redirect │
│                                                            │
│  OAuth (Social Login):                                     │
│  Redirect → Provider Auth → Callback → Upsert User → Done │
│                                                            │
│  Magic Link:                                               │
│  Email → Generate Token → Send Link → Verify → Login       │
│                                                            │
└────────────────────────────────────────────────────────────┘
会话管理
策略优点缺点
JWT无状态、可扩展难以撤销
服务端会话可撤销、安全需要会话存储
混合兼具两者优点更复杂
安全检查清单
  • 密码哈希(bcrypt/argon2)
  • 登录速率限制
  • CSRF 防护
  • 安全 Cookie 设置(httpOnly、secure、sameSite)
  • 失败尝试后锁定账户
  • 密码重置令牌过期

管理仪表盘

数据表格模式
// Reusable data table with sorting, filtering, pagination
interface DataTableProps<T> {
  data: T[];
  columns: ColumnDef<T>[];
  pagination: { page: number; pageSize: number; total: number };
  sorting: { field: string; direction: 'asc' | 'desc' }[];
  filters: Record<string, unknown>;
  onStateChange: (state: TableState) => void;
}

// Server-side handling
async function getUsers(params: TableState) {
  const { page, pageSize, sorting, filters } = params;

  const query = {
    where: buildWhereClause(filters),
    orderBy: buildOrderBy(sorting),
    skip: (page - 1) * pageSize,
    take: pageSize,
  };

  const [users, total] = await Promise.all([
    db.user.findMany(query),
    db.user.count({ where: query.where })
  ]);

  return { data: users, total };
}
批量操作
// Safe bulk delete with confirmation
async function bulkDelete(ids: string[]) {
  // 1. Validate permissions for each item
  const items = await db.item.findMany({
    where: { id: { in: ids } },
    select: { id: true, ownerId: true }
  });

  const authorized = items.filter(item =>
    canDelete(currentUser, item)
  );

  // 2. Soft delete or hard delete
  await db.item.updateMany({
    where: { id: { in: authorized.map(i => i.id) } },
    data: { deletedAt: new Date() }
  });

  return {
    deleted: authorized.length,
    skipped: ids.length - authorized.length
  };
}

文件管理

上传策略
方法使用场景最大大小
直传服务器小文件~10MB
预签名 URL大文件无限制
分块上传超大文件无限制
可断点续传网络不稳定无限制
预签名 URL 流程
Client                    Server                    S3
   │                         │                       │
   │── Request upload URL ──→│                       │
   │                         │── Generate presigned ─→│
   │←── Return presigned URL─│                       │
   │                         │                       │
   │───────── Upload file directly ─────────────────→│
   │                         │                       │
   │── Confirm upload ──────→│                       │
   │                         │── Verify file exists ─→│
   │←── Success ─────────────│                       │
图像处理流水线
async function processUpload(file: File) {
  // 1. Validate file type and size
  if (!ALLOWED_TYPES.includes(file.type)) {
    throw new Error('Invalid file type');
  }

  // 2. Generate variants
  const variants = await Promise.all([
    sharp(file.buffer).resize(100, 100).toBuffer(),   // thumbnail
    sharp(file.buffer).resize(800, 600).toBuffer(),   // medium
    sharp(file.buffer).resize(1920, 1080).toBuffer(), // large
  ]);

  // 3. Upload to CDN
  const urls = await uploadToS3(variants);

  // 4. Store metadata
  return db.image.create({
    data: {
      original: urls.original,
      thumbnail: urls.thumbnail,
      medium: urls.medium,
      large: urls.large,
      mimeType: file.type,
      size: file.size,
    }
  });
}

搜索实现

搜索架构
┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│   Database   │ ──→ │    Sync      │ ──→ │   Search     │
│  (Primary)   │     │   Worker     │     │   Engine     │
└──────────────┘     └──────────────┘     └──────────────┘
                                                  ↑
                                                  │
┌──────────────┐     ┌──────────────┐             │
│    Client    │ ──→ │  Search API  │ ────────────┘
└──────────────┘     └──────────────┘
搜索功能检查清单
  • 全文搜索
  • 分面筛选
  • 自动补全/建议
  • 拼写容错(模糊匹配)
  • 高亮显示
  • 同义词
  • 相关性调优

工作流引擎

状态机模式
const orderStateMachine = {
  initial: 'pending',
  states: {
    pending: {
      on: {
        PAY: 'paid',
        CANCEL: 'cancelled'
      }
    },
    paid: {
      on: {
        SHIP: 'shipped',
        REFUND: 'refunded'
      }
    },
    shipped: {
      on: {
        DELIVER: 'delivered',
        RETURN: 'returned'
      }
    },
    delivered: { type: 'final' },
    cancelled: { type: 'final' },
    refunded: { type: 'final' },
    returned: {
      on: {
        REFUND: 'refunded'
      }
    }
  }
};
审批工作流
interface ApprovalStep {
  id: string;
  approvers: string[];        // User IDs or roles
  requiredApprovals: number;  // How many need to approve
  timeout?: Duration;         // Auto-escalate after
  escalateTo?: string;        // Next approver on timeout
}

async function processApproval(stepId: string, userId: string, decision: 'approve' | 'reject') {
  const step = await db.approvalStep.findUnique({ where: { id: stepId } });

  // Record decision
  await db.approval.create({
    data: { stepId, userId, decision, timestamp: new Date() }
  });

  // Check if complete
  const approvals = await db.approval.count({
    where: { stepId, decision: 'approve' }
  });

  if (approvals >= step.requiredApprovals) {
    await advanceToNextStep(step);
  }
}

多语言(i18n)

翻译结构
locales/
├── en/
│   ├── common.json    # Shared strings
│   ├── auth.json      # Auth module
│   └── dashboard.json # Dashboard module
├── zh-TW/
│   ├── common.json
│   ├── auth.json
│   └── dashboard.json
└── ja/
    └── ...
最佳实践
  1. 键命名:使用命名空间键

    {
      "auth.login.title": "Sign In",
      "auth.login.email": "Email Address",
      "auth.login.submit": "Sign In"
    }
    
  2. 复数化:处理复数形式

    {
      "items": "{count, plural, =0 {No items} =1 {1 item} other {# items}}"
    }
    
  3. 变量:使用插值

    {
      "welcome": "Welcome, {name}!"
    }
    
  4. 日期/数字格式化:使用 Intl API

    new Intl.DateTimeFormat(locale).format(date)
    new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount)
    

相关技能

  • [[architecture-patterns]] - 整体系统设计
  • [[frontend]] - UI 实现
  • [[backend]] - 服务端实现
  • [[database]] - 数据持久化
  • [[security-practices]] - 安全注意事项

评论

支持 Markdown