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

NestJS中如何定义带动态股票代码键的OpenAPI响应类型?

NestJS中定义动态键的股票响应类型方案

1. TypeScript类型定义:用索引签名实现动态键

直接通过TypeScript的索引签名定义动态键的对象结构,无需维护固定的股票代码列表,自动适配任意数量的股票:

// 单个股票的数据结构类(用于Swagger文档生成)
import { ApiProperty } from '@nestjs/swagger';

export class Stock {
  @ApiProperty({ example: 200, description: '请求状态码' })
  status: number;

  @ApiProperty({ example: true, description: '是否可交易' })
  tradable: boolean;

  @ApiProperty({ example: true, description: '是否支持 fractional trading' })
  fractionable: boolean;

  @ApiProperty({ example: 'AAPL', description: '股票代码' })
  symbol: string;
}

// 动态键的响应数据类型:键为任意字符串(股票代码),值为Stock类型
export type StockMap = {
  [symbol: string]: Stock;
};

// 完整的响应DTO
import { ApiProperty, ApiExtraModels, getSchemaPath } from '@nestjs/swagger';

@ApiExtraModels(Stock) // 告诉Swagger识别Stock类
export class StockResponseDto {
  @ApiProperty({
    type: 'object',
    additionalProperties: {
      $ref: getSchemaPath(Stock), // 关联Stock的Schema定义
    },
    description: '以股票代码为键的股票状态集合',
  })
  data: StockMap;
}

2. 在控制器中使用

直接将DTO作为响应类型返回,NestJS会自动做类型校验,Swagger也能生成正确的文档:

import { Controller, Get } from '@nestjs/common';
import { ApiResponse } from '@nestjs/swagger';
import { StockResponseDto } from './dto/stock-response.dto';

@Controller('stocks')
export class StocksController {
  @Get('statuses')
  @ApiResponse({ status: 200, type: StockResponseDto })
  getStockStatuses(): StockResponseDto {
    // 这里可以替换为从数据库/第三方接口动态获取的股票数据
    return {
      data: {
        AAPL: { status: 200, tradable: true, fractionable: true, symbol: 'AAPL' },
        MCFT: { status: 200, tradable: true, fractionable: true, symbol: 'MCFT' },
        // 支持任意新增的股票代码,无需修改类型定义
      },
    };
  }
}

3. 核心优势

  • 完全动态化:不需要维护固定的股票代码列表,新增/删除股票代码时无需修改类型定义
  • 类型安全:TypeScript会自动校验每个股票对象的结构是否符合Stock定义
  • OpenAPI文档兼容:通过Swagger的additionalProperties配置,文档能正确显示动态键的结构,前端开发者可以清晰了解响应格式

内容的提问来源于stack exchange,提问作者Kevin Loo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:45:36