You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nestjs/Prisma REST API问题:查询指定货架盒子返回404

问题分析与解决方案

你的问题主要出在查询返回结构不匹配、Swagger响应类型错误以及未处理货架不存在的场景这几个点上,以下是具体的修复步骤:

1. 修正Service层的查询逻辑

原查询通过shelf.findUnique返回的是包含boxes字段的对象(格式为{ boxes: Box[] }),而非直接的Box数组,且当货架ID不存在时,findUnique会返回null,NestJS默认对null返回404状态码。

推荐方案:直接查询Box表(更高效)

// shelves.service.ts
getBoxes(id: string) {
  return this.prisma.box.findMany({
    where: { shelfId: id },
    // 后续需要获取盒子内物品时,可添加关联查询:
    // include: { items: true }
  });
}

备选方案:保留货架查询并处理空值

如果需要先验证货架是否存在,再返回盒子列表:

// shelves.service.ts
import { NotFoundException } from '@nestjs/common';

async getBoxes(id: string) {
  const shelf = await this.prisma.shelf.findUnique({
    where: { id },
    select: { boxes: true }
  });
  
  if (!shelf) {
    throw new NotFoundException('指定货架不存在');
  }
  
  return shelf.boxes;
}

2. 修正Controller层的Swagger响应类型

当前@ApiOkResponse标注的是ShelfEntity数组,但实际返回的是Box数组,需要先定义BoxEntity,再更新注解:

定义BoxEntity

// box.entity.ts
import { ApiProperty } from '@nestjs/swagger';
import { Box } from '@prisma/client';

export class BoxEntity implements Box {
  @ApiProperty({ required: true })
  id: string;

  @ApiProperty({ required: true })
  shelfId: string;

  // 后续需要返回物品时,添加对应属性:
  // @ApiProperty({ type: () => [ItemEntity], required: false })
  // items: ItemEntity[];
}

更新控制器注解

// shelves.controller.ts
import { BoxEntity } from './../box/box.entity'; // 根据实际文件路径调整

@Get(':id/boxes') 
@ApiOkResponse({ type: BoxEntity, isArray: true })
getBoxes(@Param('id') id:string ){
    return this.shelvesService.getBoxes(id)
}

3. 可选:处理货架不存在的404场景

如果使用直接查询Box表的方案,当货架不存在时会返回空数组。若需要此时返回404,可在Service中先校验货架存在性:

async getBoxes(id: string) {
  const shelfExists = await this.prisma.shelf.findUnique({
    where: { id },
    select: { id: true }
  });
  
  if (!shelfExists) {
    throw new NotFoundException('指定货架不存在');
  }
  
  return this.prisma.box.findMany({ where: { shelfId: id } });
}

内容的提问来源于stack exchange,提问作者Jarrod.Clark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:05:41