API 开发指南

本文档介绍 Vibany 项目的 API 架构和开发规范,帮助开发者理解和扩展 API 功能。

API 架构概述

Vibany 使用 Next.js App Router 的 API Routes,基于文件系统自动路由。

目录结构

app/api/
├── admin/                      # 管理员 API(需要管理员权限)
│   ├── dashboard/stats/        # GET - 仪表板统计数据
│   ├── users/                  # GET/POST - 用户列表/创建
│   ├── orders/                 # GET - 订单列表
│   ├── invitations/            # GET/POST - 邀请码管理
│   └── backup/image/           # POST - 图片备份
├── chat/prompts/               # POST - AI 提示词生成
├── draw/                       # POST - 图像生成
├── me/                         # GET - 当前用户信息
├── orders/                     # GET - 订单列表
├── purchase/                   # POST - 创建购买订单
└── public/                     # 公开 API(无需认证)
    ├── backup/                 # GET - 触发备份任务
    ├── clear/                  # GET - 清理临时文件
    ├── epay/notify/            # POST - 易支付回调
    └── stripe/notify/          # POST - Stripe 回调

认证与授权

1. Clerk 认证

所有需要认证的 API 使用 Clerk 进行身份验证:

import { auth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
  const { userId } = await auth();
  
  if (!userId) {
    return new NextResponse("Unauthorized", { status: 401 });
  }
  
  // 处理请求...
}

2. 管理员权限检查

export async function adminAuth() {
  const { userId } = await auth();
  
  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  
  const adminIds = process.env.ADMIN_USER_IDS?.split(',') || [];
  const isAdmin = adminIds.includes(userId);
  
  if (!isAdmin) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }
  
  return null; // 验证通过返回 null
}

// 使用示例
export async function GET(request: Request) {
  const authResponse = await adminAuth();
  if (authResponse) return authResponse;
  
  // 管理员逻辑...
}

标准响应格式

成功响应

interface SuccessResponse<T> {
  data: T;
  message?: string;
  pagination?: {
    page: number;
    limit: number;
    totalCount: number;
    totalPages: number;
    hasNextPage: boolean;
    hasPrevPage: boolean;
  };
}

// 示例
return NextResponse.json({
  data: userList,
  pagination: {
    page: 1,
    limit: 10,
    totalCount: 100,
    totalPages: 10,
    hasNextPage: true,
    hasPrevPage: false
  }
});

错误响应

interface ErrorResponse {
  code: string;
  message: string;
  details?: any;
  timestamp: string;
  path: string;
}

// 示例
return NextResponse.json({
  code: "INSUFFICIENT_POINTS",
  message: "积分不足",
  timestamp: new Date().toISOString(),
  path: "/api/draw"
}, { status: 400 });

分页查询

标准分页实现

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get('page') || '1');
  const limit = parseInt(searchParams.get('limit') || '10');
  const search = searchParams.get('search') || '';
  
  // 构建查询条件
  const conditions = [];
  if (search) {
    conditions.push(
      or(
        ilike(users.email, `%${search}%`),
        ilike(users.username, `%${search}%`)
      )
    );
  }
  
  // 分页查询
  const offset = (page - 1) * limit;
  const [data, totalResult] = await Promise.all([
    db.query.users.findMany({
      where: and(...conditions),
      limit,
      offset,
      orderBy: [desc(users.createdAt)]
    }),
    db.select({ count: sql<number>`count(*)` })
      .from(users)
      .where(and(...conditions))
  ]);
  
  const totalCount = totalResult[0]?.count || 0;
  
  return NextResponse.json({
    data,
    pagination: {
      page,
      limit,
      totalCount,
      totalPages: Math.ceil(totalCount / limit),
      hasNextPage: page * limit < totalCount,
      hasPrevPage: page > 1
    }
  });
}

流式响应

AI 提示词生成(流式)

import { createDataStreamResponse, streamText } from "ai";

export async function POST(request: Request) {
  const { userId } = await auth();
  if (!userId) {
    return new NextResponse("Unauthorized", { status: 401 });
  }
  
  const { messages, model } = await request.json();
  
  // 检查积分...
  
  return createDataStreamResponse({
    execute: (dataStream) => {
      return streamText({
        model: myProvider.languageModel(model),
        messages,
        onChunk: ({ chunk }) => {
          dataStream.writeData({ text: chunk.text });
        },
        onFinish: ({ text }) => {
          dataStream.writeData({ done: true });
        }
      });
    }
  });
}

图像生成(流式/异步)

export async function POST(request: Request) {
  const { userId } = await auth();
  
  // 检查并发限制
  const pendingDraws = await getUserPendingDraws(userId);
  
  if (pendingDraws.length >= MAX_CONCURRENT_DRAWS) {
    // 异步模式
    const historyId = await createHistory({...});
    
    // 异步处理
    processDrawRequest({...}).catch(console.error);
    
    return NextResponse.json({
      mode: 'async',
      historyId,
      message: '图像生成已加入队列'
    });
  }
  
  // 同步流式模式
  return new Response(
    new ReadableStream({
      async start(controller) {
        // 流式返回生成进度...
      }
    }),
    { headers: { 'Content-Type': 'text/event-stream' } }
  );
}

错误处理

统一错误处理

// lib/api/error-handler.ts
export enum ApiErrorCode {
  INSUFFICIENT_POINTS = 'INSUFFICIENT_POINTS',
  MODEL_NOT_FOUND = 'MODEL_NOT_FOUND',
  INVALID_PARAMETERS = 'INVALID_PARAMETERS',
  RATE_LIMITED = 'RATE_LIMITED',
  INTERNAL_ERROR = 'INTERNAL_ERROR'
}

export class ApiError extends Error {
  constructor(
    public code: ApiErrorCode,
    message: string,
    public status: number = 500,
    public details?: any
  ) {
    super(message);
  }
}

export function handleApiError(error: unknown): NextResponse {
  if (error instanceof ApiError) {
    return NextResponse.json({
      code: error.code,
      message: error.message,
      details: error.details,
      timestamp: new Date().toISOString()
    }, { status: error.status });
  }
  
  console.error('Unhandled error:', error);
  
  return NextResponse.json({
    code: ApiErrorCode.INTERNAL_ERROR,
    message: 'Internal Server Error',
    timestamp: new Date().toISOString()
  }, { status: 500 });
}

// 使用示例
export async function POST(request: Request) {
  try {
    // API 逻辑...
  } catch (error) {
    return handleApiError(error);
  }
}

限流控制

内存限流实现

// lib/rate-limit/index.ts
const rateLimitMap = new Map<string, { count: number; resetTime: number }>();

export function rateLimit(key: string, limit: number, windowMs: number) {
  const now = Date.now();
  const record = rateLimitMap.get(key);
  
  if (!record || now > record.resetTime) {
    rateLimitMap.set(key, { count: 1, resetTime: now + windowMs });
    return { success: true, remaining: limit - 1 };
  }
  
  if (record.count >= limit) {
    return { 
      success: false, 
      remaining: 0, 
      resetTime: record.resetTime 
    };
  }
  
  record.count++;
  return { success: true, remaining: limit - record.count };
}

// 使用示例
export async function POST(request: Request) {
  const { userId } = await auth();
  
  const rateLimitResult = rateLimit(`user:${userId}`, 100, 60000);
  
  if (!rateLimitResult.success) {
    return NextResponse.json(
      { error: "Rate limit exceeded" },
      { 
        status: 429,
        headers: {
          'X-RateLimit-Remaining': '0',
          'X-RateLimit-Reset': new Date(rateLimitResult.resetTime).toISOString()
        }
      }
    );
  }
  
  // 继续处理...
}

支付回调处理

易支付回调

// app/api/public/epay/notify/route.ts
export async function POST(request: Request) {
  const formData = await request.formData();
  const params: Record<string, string> = {};
  
  formData.forEach((value, key) => {
    params[key] = value.toString();
  });
  
  // 验证签名
  const isValid = verifyRSASignature(params);
  if (!isValid) {
    return new Response('Invalid signature', { status: 400 });
  }
  
  const { out_trade_no, trade_status } = params;
  
  if (trade_status === 'TRADE_SUCCESS') {
    const order = await db.query.orders.findFirst({
      where: eq(orders.outTradeNo, out_trade_no)
    });
    
    if (order && order.status !== 'SUCCESS') {
      // 更新订单
      await db.update(orders)
        .set({ status: 'SUCCESS', paidAt: new Date() })
        .where(eq(orders.id, order.id));
      
      // 充值积分
      await rechargeUserPoints({...});
    }
  }
  
  return new Response('success');
}

Stripe Webhook

// app/api/public/stripe/notify/route.ts
export async function POST(request: Request) {
  const body = await request.text();
  const signature = request.headers.get('stripe-signature');
  
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      body, 
      signature!, 
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (err) {
    return new Response('Invalid signature', { status: 400 });
  }
  
  switch (event.type) {
    case 'checkout.session.completed':
      await handleCheckoutCompleted(event.data.object);
      break;
  }
  
  return new Response('Webhook handled');
}

开发新 API

1. 创建路由文件

// app/api/my-feature/route.ts
import { auth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { db } from "@/lib/db";

export async function GET(request: Request) {
  const { userId } = await auth();
  if (!userId) {
    return new NextResponse("Unauthorized", { status: 401 });
  }
  
  // 实现逻辑...
  
  return NextResponse.json({ data: result });
}

export async function POST(request: Request) {
  const { userId } = await auth();
  if (!userId) {
    return new NextResponse("Unauthorized", { status: 401 });
  }
  
  const body = await request.json();
  
  // 验证输入...
  // 业务逻辑...
  
  return NextResponse.json({ data: result }, { status: 201 });
}

2. 添加类型定义

// types/my-feature.ts
export interface MyFeatureRequest {
  name: string;
  description?: string;
}

export interface MyFeatureResponse {
  id: string;
  name: string;
  createdAt: string;
}

3. 添加测试

创建 .http 文件进行 API 测试:

### Get My Feature
GET http://localhost:3000/api/my-feature
Authorization: Bearer {{token}}

### Create My Feature
POST http://localhost:3000/api/my-feature
Content-Type: application/json
Authorization: Bearer {{token}}

{
  "name": "Test",
  "description": "Test description"
}

最佳实践

1. 输入验证

import { z } from "zod";

const schema = z.object({
  name: z.string().min(1).max(100),
  email: z.string().email(),
  age: z.number().min(0).max(150).optional()
});

const result = schema.safeParse(body);
if (!result.success) {
  return NextResponse.json(
    { error: "Invalid input", details: result.error.errors },
    { status: 400 }
  );
}

2. 日志记录

import { logger } from "@/lib/logger";

export async function POST(request: Request) {
  logger.info('API called', { path: '/api/my-feature', userId });
  
  try {
    // 业务逻辑...
    logger.info('API success', { result });
    return NextResponse.json({ data: result });
  } catch (error) {
    logger.error('API error', { error, userId });
    return handleApiError(error);
  }
}

3. 性能优化

  • 使用数据库索引
  • 实现请求缓存
  • 异步处理耗时操作
  • 限制返回数据量

相关文档

© copyright Justin 2026. All rights reserved.