自定义功能开发指南

本文档介绍如何在 Vibany 项目中开发自定义功能,包括新增页面、修改业务逻辑和集成新服务。

开发环境准备

1. 克隆项目

git clone https://github.com/your-repo/vibany-next.git
cd vibany-next

2. 安装依赖

npm install
# 或
pnpm install

3. 配置环境变量

cp .env.example .env.local
# 编辑 .env.local 配置必要的环境变量

4. 启动开发服务器

npm run dev
# 访问 http://localhost:3000

新增页面

1. 创建页面文件

Next.js App Router 使用文件系统路由:

// app/my-feature/page.tsx
import { auth } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";

export default async function MyFeaturePage() {
  const { userId } = await auth();
  
  if (!userId) {
    redirect("/login");
  }
  
  return (
    <div className="container mx-auto py-8">
      <h1 className="text-3xl font-bold">我的功能</h1>
      {/* 页面内容 */}
    </div>
  );
}

2. 添加元数据

import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "我的功能 | Vibany",
  description: "功能描述",
};

3. 添加导航链接

在侧边栏或导航中添加链接:

// components/navbar.tsx
const navItems = [
  { label: "首页", href: "/" },
  { label: "AI 绘图", href: "/draw" },
  { label: "我的功能", href: "/my-feature" },
];

新增 API

1. 创建 API 路由

// 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 });
  }
  
  // 查询数据
  const data = await db.query.myTable.findMany({
    where: eq(myTable.userId, userId)
  });
  
  return NextResponse.json({ data });
}

export async function POST(request: Request) {
  const { userId } = await auth();
  if (!userId) {
    return new NextResponse("Unauthorized", { status: 401 });
  }
  
  const body = await request.json();
  
  // 验证输入
  if (!body.name) {
    return NextResponse.json(
      { error: "Name is required" },
      { status: 400 }
    );
  }
  
  // 插入数据
  const result = await db.insert(myTable).values({
    id: nanoid(),
    userId,
    name: body.name,
    createdAt: new Date()
  }).returning();
  
  return NextResponse.json({ data: result[0] }, { status: 201 });
}

2. 前端调用 API

// hooks/use-my-feature.ts
import useSWR from "swr";

const fetcher = (url: string) => fetch(url).then(r => r.json());

export function useMyFeature() {
  const { data, error, mutate } = useSWR("/api/my-feature", fetcher);
  
  const createItem = async (name: string) => {
    const res = await fetch("/api/my-feature", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name })
    });
    
    if (res.ok) {
      mutate(); // 刷新数据
    }
    
    return res;
  };
  
  return { data, error, createItem };
}

修改数据库 Schema

1. 编辑 Schema

// lib/db/schema.ts
import { pgTable, text, timestamp, integer, jsonb } from "drizzle-orm/pg-core";

export const myTable = pgTable("my_table", {
  id: text("id").primaryKey(),
  userId: text("user_id").notNull(),
  name: text("name").notNull(),
  extra: jsonb("extra").default({}).notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
  updatedAt: timestamp("updated_at").defaultNow().notNull(),
});

2. 生成迁移

npm run db:generate

3. 应用迁移

开发环境:

npm run db:push

生产环境:

npm run db:migrate

4. 更新类型

// types/my-table.ts
import { myTable } from "@/lib/db/schema";

export type MyTable = typeof myTable.$inferSelect;
export type NewMyTable = typeof myTable.$inferInsert;

新增 AI 模型

1. 配置模型

// constants/draw/models.ts
export const DRAW_MODELS: Record<string, DrawModel> = {
  // 现有模型...
  
  "my-new-model": {
    id: "my-new-model",
    type: "image",
    brand: "MyBrand",
    name: "我的新模型",
    description: "模型描述",
    paidOnly: false,
    disabled: false,
    points: 10,
    maxImages: 4
  }
};

2. 实现模型调用

// lib/ai/my-provider.ts
import { generateImage } from "ai";

export async function generateWithMyModel(prompt: string, options: GenerateOptions) {
  const result = await generateImage({
    model: myProvider.imageModel("my-model-id"),
    prompt,
    ...options
  });
  
  return result;
}

3. 集成到生成流程

// lib/draw/image-requests.ts
import { generateWithMyModel } from "@/lib/ai/my-provider";

export async function processDrawRequest(params: DrawParams) {
  const { model, prompt, images } = params;
  
  switch (model) {
    case "my-new-model":
      return generateWithMyModel(prompt, {
        size: "1024x1024",
        // 其他参数...
      });
    
    // 其他模型...
  }
}

新增支付方式

1. 创建支付服务

// lib/payment/my-payment.ts
export class MyPaymentService {
  private apiKey: string;
  private apiUrl: string;
  
  constructor() {
    this.apiKey = process.env.MY_PAYMENT_API_KEY!;
    this.apiUrl = process.env.MY_PAYMENT_API_URL!;
  }
  
  async createOrder(params: CreateOrderParams) {
    const response = await fetch(`${this.apiUrl}/create-order`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${this.apiKey}`
      },
      body: JSON.stringify(params)
    });
    
    return response.json();
  }
  
  verifySignature(params: Record<string, string>, signature: string) {
    // 验证签名逻辑...
    return true;
  }
}

2. 创建回调处理

// app/api/public/my-payment/notify/route.ts
export async function POST(request: Request) {
  const body = await request.json();
  const signature = request.headers.get("x-signature");
  
  // 验证签名
  const paymentService = new MyPaymentService();
  const isValid = paymentService.verifySignature(body, signature!);
  
  if (!isValid) {
    return new Response("Invalid signature", { status: 400 });
  }
  
  // 处理支付成功
  if (body.status === "success") {
    await processPaymentSuccess(body.orderId);
  }
  
  return new Response("OK");
}

自定义组件

1. 创建组件

// components/my-feature/my-component.tsx
"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";

interface MyComponentProps {
  title: string;
  onAction: () => void;
}

export function MyComponent({ title, onAction }: MyComponentProps) {
  const [loading, setLoading] = useState(false);
  
  const handleClick = async () => {
    setLoading(true);
    await onAction();
    setLoading(false);
  };
  
  return (
    <div className="rounded-lg border p-4">
      <h3 className="text-lg font-semibold">{title}</h3>
      <Button onClick={handleClick} disabled={loading}>
        {loading ? "处理中..." : "执行"}
      </Button>
    </div>
  );
}

2. 使用 shadcn/ui 组件

npx shadcn@latest add button
npx shadcn@latest add card
npx shadcn@latest add dialog

添加计划任务

1. 创建定时任务 API

// app/api/public/my-cron/route.ts
import { NextResponse } from "next/server";

export async function GET(request: Request) {
  // 验证 Cron Secret
  const { searchParams } = new URL(request.url);
  const secret = searchParams.get("secret");
  
  if (secret !== process.env.CRON_SECRET) {
    return new Response("Unauthorized", { status: 401 });
  }
  
  // 执行任务
  await runScheduledTask();
  
  return NextResponse.json({ success: true });
}

async function runScheduledTask() {
  // 定时任务逻辑...
  console.log("定时任务执行完成");
}

2. 配置 Vercel Cron

// vercel.json
{
  "crons": [
    {
      "path": "/api/public/my-cron?secret=CRON_SECRET",
      "schedule": "0 0 * * *"
    }
  ]
}

最佳实践

1. 代码规范

  • 使用 TypeScript 严格模式
  • 遵循 ESLint 规则
  • 组件使用 PascalCase
  • 文件使用 kebab-case

2. 性能优化

  • 使用 React.memo 优化组件
  • 图片使用 Next.js Image 组件
  • API 响应使用缓存
  • 大数据量使用分页

3. 安全考虑

  • 所有 API 验证用户身份
  • 敏感操作添加二次确认
  • 防止 SQL 注入(使用 ORM)
  • XSS 防护(使用 dangerouslySetInnerHTML 时小心)

4. 测试

创建测试文件:

// test/my-feature.http
### Get My Feature Data
GET http://localhost:3000/api/my-feature
Authorization: Bearer {{clerk_token}}

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

{
  "name": "Test Item"
}

调试技巧

1. 使用 console.log

console.log("Debug info", { userId, data });
console.error("Error details", error);

2. 使用 React DevTools

安装浏览器扩展调试 React 组件。

3. 使用 Drizzle Studio

npm run db:studio

4. 使用 VS Code 调试

配置 .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Next.js: debug full stack",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/.bin/next",
      "args": ["dev"],
      "console": "integratedTerminal"
    }
  ]
}

部署前检查清单

  • 代码通过 ESLint 检查
  • TypeScript 无错误
  • 数据库迁移已生成
  • 环境变量已更新
  • 功能已测试
  • 文档已更新

相关文档

© copyright Justin 2026. All rights reserved.