routes.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Router, Request, Response, NextFunction } from 'express';
  2. import { PinterestApi } from './api.ts';
  3. import { PinterestConfig } from './types.ts';
  4. // 统一响应格式
  5. const sendResponse = (res: Response, data: any) => {
  6. res.json({
  7. success: true,
  8. data,
  9. timestamp: new Date().toISOString()
  10. });
  11. };
  12. const asyncHandler = (fn: (req: Request, res: Response, next: NextFunction) => Promise<any>) =>
  13. (req: Request, res: Response, next: NextFunction) => {
  14. Promise.resolve(fn(req, res, next)).catch(next);
  15. };
  16. /**
  17. * 创建 Pinterest 路由
  18. * @param config 配置对象
  19. */
  20. export const createPinterestRouter = (config?: PinterestConfig) => {
  21. const router = Router();
  22. const api = new PinterestApi(config);
  23. // 1. Pinterest 搜索用户
  24. // GET /search?keyword=fashion&country=US
  25. router.get('/search', asyncHandler(async (req, res) => {
  26. const { keyword, country } = req.query;
  27. if (!keyword) {
  28. throw new Error('Keyword is required');
  29. }
  30. const result = await api.searchUsers({
  31. keyword: String(keyword),
  32. country: country ? String(country) : undefined
  33. });
  34. sendResponse(res, result);
  35. }));
  36. // 2. Pinterest 获取用户帖子
  37. // GET /users/posts?url=https://www.pinterest.com/username/&count=20
  38. router.get('/users/posts', asyncHandler(async (req, res) => {
  39. const { url, count } = req.query;
  40. if (!url) {
  41. throw new Error('User Profile URL is required');
  42. }
  43. const result = await api.getUserPosts({
  44. url: String(url),
  45. count: count ? Number(count) : 20
  46. });
  47. sendResponse(res, result);
  48. }));
  49. // 3. Pinterest 获取帖子评论
  50. // GET /posts/comments?url=https://www.pinterest.com/pin/123/
  51. router.get('/posts/comments', asyncHandler(async (req, res) => {
  52. const { url } = req.query;
  53. if (!url) {
  54. throw new Error('Post URL is required');
  55. }
  56. const result = await api.getPostComments({
  57. url: String(url)
  58. });
  59. sendResponse(res, result);
  60. }));
  61. return router;
  62. };