import { Router, Request, Response, NextFunction } from 'express'; import { PinterestApi } from './api.ts'; import { PinterestConfig } from './types.ts'; // 统一响应格式 const sendResponse = (res: Response, data: any) => { res.json({ success: true, data, timestamp: new Date().toISOString() }); }; const asyncHandler = (fn: (req: Request, res: Response, next: NextFunction) => Promise) => (req: Request, res: Response, next: NextFunction) => { Promise.resolve(fn(req, res, next)).catch(next); }; /** * 创建 Pinterest 路由 * @param config 配置对象 */ export const createPinterestRouter = (config?: PinterestConfig) => { const router = Router(); const api = new PinterestApi(config); // 1. Pinterest 搜索用户 // GET /search?keyword=fashion&country=US router.get('/search', asyncHandler(async (req, res) => { const { keyword, country } = req.query; if (!keyword) { throw new Error('Keyword is required'); } const result = await api.searchUsers({ keyword: String(keyword), country: country ? String(country) : undefined }); sendResponse(res, result); })); // 2. Pinterest 获取用户帖子 // GET /users/posts?url=https://www.pinterest.com/username/&count=20 router.get('/users/posts', asyncHandler(async (req, res) => { const { url, count } = req.query; if (!url) { throw new Error('User Profile URL is required'); } const result = await api.getUserPosts({ url: String(url), count: count ? Number(count) : 20 }); sendResponse(res, result); })); // 3. Pinterest 获取帖子评论 // GET /posts/comments?url=https://www.pinterest.com/pin/123/ router.get('/posts/comments', asyncHandler(async (req, res) => { const { url } = req.query; if (!url) { throw new Error('Post URL is required'); } const result = await api.getPostComments({ url: String(url) }); sendResponse(res, result); })); return router; };