如何在NestJS的POST接口中传递对象数组?
实现请求体单个字段传递对象数组的改造步骤
当前需要将原有接收字符串数组的sponsor字段,改为接收对象数组,以下是具体改造方案:
1. 定义Sponsor子DTO
首先创建单个赞助商的DTO类,用于描述请求体中每个sponsor对象的结构:
import { ApiProperty } from '@nestjs/swagger'; export class SponsorDTO { @ApiProperty({ name: 'sponsorName' }) sponsorName: string; @ApiProperty({ name: 'legalStatus' }) legalStatus: string; @ApiProperty({ name: 'formationYear' }) formationYear: string; }
2. 修改FinancialProposalDTO
将原有的sponsors字符串数组类型替换为SponsorDTO数组,同时对齐请求体中的字段名(将sponsors改为sponsor):
import { ApiProperty } from '@nestjs/swagger'; import { SponsorDTO } from './sponsor.dto'; // 引入子DTO export class FinancialProposalDTO { @ApiProperty({ name: 'sponsor', type: [SponsorDTO] }) sponsor: SponsorDTO[]; @ApiProperty({ name: 'totalCostOfExecution' }) totalCostOfExecution: string; @ApiProperty({ name: 'equity' }) equity: string; @ApiProperty({ name: 'debtOrLoan' }) debtOrLoan: string; }
3. 更新Entity存储结构
原Entity中sponsor字段为字符串数组,现在需要改为存储JSON对象数组。根据Sequelize特性,使用DataType.JSONB(推荐,支持查询)或DataType.JSON类型:
import { Table, Column, Model, DataType } from 'sequelize-typescript'; @Table export class FinancialProposal extends Model { @Column({ type: DataType.JSONB, // 或 DataType.JSON,根据数据库支持情况选择 allowNull: false }) sponsor: Array<{ sponsorName: string; legalStatus: string; formationYear: string; }>; @Column({ type: DataType.STRING, }) totalCostOfExecution: string; @Column({ type: DataType.STRING, }) equity: string; @Column({ type: DataType.STRING, }) debtOrLoan: string; // 补充关联的applicationId字段(若之前未定义) @Column({ type: DataType.INTEGER, // 根据实际ID类型调整 allowNull: false }) applicationId: number; }
4. 调整Controller和Service
确保请求体类型绑定正确,数据处理逻辑匹配:
Controller修改
import { Body, Param, Post, Public } from '@nestjs/common'; import { FinancialProposalDTO } from './dto/financial-proposal.dto'; @Public() @Post('/:id/financialProposals') async submitFinancialProposal( @Param('id') applicationId: number, // 明确参数类型 @Body() body: FinancialProposalDTO // 绑定DTO类型,自动做格式校验 ) { await this.applicationService.submitFinancialProposal(applicationId, body); return SUCCESS; }
Service修改
import { Injectable } from '@nestjs/common'; import { FinancialProposalDTO } from './dto/financial-proposal.dto'; import { FinancialProposal } from './entities/financial-proposal.entity'; @Injectable() export class ApplicationService { constructor(private readonly financialRepository: typeof FinancialProposal) {} async submitFinancialProposal(applicationId: number, data: FinancialProposalDTO) { return await this.financialRepository.create({ ...data, applicationId // 确保字段名与Entity一致 }); } }
注意事项
- 确认数据库支持JSON/JSONB类型(如PostgreSQL支持JSONB,MySQL支持JSON);
- Swagger会自动根据DTO生成符合预期的请求体示例;
- 若需对sponsor数组内的字段做校验,可在
SponsorDTO中添加class-validator装饰器(如@IsString()、@IsNotEmpty()等)。
内容的提问来源于stack exchange,提问作者hamza_dilber
相关产品推荐
相关产品推荐

