| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from '@hono/zod-openapi';
- import { GoodsSchema } from '../schemas/goods.schema.js';
- import { ErrorSchema } from '@d8d/shared-utils';
- import { AppDataSource } from '@d8d/shared-utils';
- import { Goods } from '../entities/goods.entity.js';
- import { AuthContext } from '@d8d/shared-types';
- import { authMiddleware } from '@d8d/auth-module';
- import { RandomGoodsQuerySchema, RandomGoodsResponseSchema } from '../schemas/random.schema.js';
- import { parseWithAwait } from '@d8d/shared-utils';
- // 定义随机商品列表路由
- const routeDef = createRoute({
- method: 'get',
- path: '/',
- middleware: [],
- request: {
- query: RandomGoodsQuerySchema
- },
- responses: {
- 200: {
- description: '成功获取随机商品列表',
- content: {
- 'application/json': {
- schema: RandomGoodsResponseSchema
- }
- }
- },
- 400: {
- description: '请求参数错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- },
- 500: {
- description: '服务器错误',
- content: {
- 'application/json': {
- schema: ErrorSchema
- }
- }
- }
- }
- });
- // 路由实现
- export const publicGoodsRandomRoutes = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- const query = c.req.valid('query');
- const { limit, categoryId, includeImages } = query;
- // 创建查询构建器
- const queryBuilder = AppDataSource.getRepository(Goods)
- .createQueryBuilder('goods')
- .where('goods.state = :state', { state: 1 }) // 只获取可用的商品
- .orderBy('RANDOM()') // 使用随机排序
- .limit(limit);
- // 如果指定了分类ID,添加分类过滤
- if (categoryId) {
- queryBuilder.andWhere(
- '(goods.category_id1 = :categoryId OR goods.category_id2 = :categoryId OR goods.category_id3 = :categoryId)',
- { categoryId }
- );
- }
- // 总是加载基础关联关系
- queryBuilder
- .leftJoinAndSelect('goods.category1', 'category1')
- .leftJoinAndSelect('goods.supplier', 'supplier')
- .leftJoinAndSelect('goods.merchant', 'merchant');
- // 如果需要包含图片关联数据
- if (includeImages) {
- queryBuilder
- .leftJoinAndSelect('goods.imageFile', 'imageFile')
- .leftJoinAndSelect('imageFile.uploadUser', 'imageUploadUser')
- .leftJoinAndSelect('goods.category2', 'category2')
- .leftJoinAndSelect('goods.category3', 'category3');
- }
- // 获取随机商品
- const goods = await queryBuilder.getMany();
- // 获取总数(用于分页参考)
- const totalQuery = AppDataSource.getRepository(Goods)
- .createQueryBuilder('goods')
- .where('goods.state = :state', { state: 1 });
- if (categoryId) {
- totalQuery.andWhere(
- 'goods.category_id1 = :categoryId OR goods.category_id2 = :categoryId OR goods.category_id3 = :categoryId',
- { categoryId }
- );
- }
- const total = await totalQuery.getCount();
- // 使用 parseWithAwait 确保数据格式正确
- const validatedGoods = await parseWithAwait(z.array(GoodsSchema), goods);
- return c.json({
- data: validatedGoods,
- total
- }, 200);
- } catch (error) {
- console.error('获取随机商品列表失败:', error);
- return c.json({
- code: 500,
- message: error instanceof Error ? error.message : '获取随机商品列表失败'
- }, 500);
- }
- });
|