nest中获取content-length

2024-08-22 21:04
文章标签 获取 length content nest

本文主要是介绍nest中获取content-length,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

mock项目中nest执行过程:

import { NestFactory } from '@nestjs/core'
import { Module, Req, Injectable, NestMiddleware, NestInterceptor, ExecutionContext, Res, Header, CallHandler, Controller, Get, MiddlewareConsumer, NestModule } from '@nestjs/common'
import { AsyncLocalStorage } from 'async_hooks'
import { Observable, throwError } from 'rxjs'
import { catchError, tap, finalize } from "rxjs/operators"
import { APP_INTERCEPTOR } from '@nestjs/core'
import { Request, Response } from 'express'// 模拟异步操作链数据存储
@Injectable()
class ClsService {als: AsyncLocalStorage<Record<string, unknown>>constructor() {this.als = new AsyncLocalStorage()}get(key: string) {return this.als.getStore()?.[key]}set(key: string, value: unknown) {if (this.als.getStore()) {(this.als.getStore() as Record<string, unknown>)[key] = value}}
}// 模拟中间件
@Injectable()
class ClsMiddleWare implements NestMiddleware {constructor(private ClsService: ClsService) {console.log('Middleware registry')}async use(req: Request, res: Response, next: () => void) {const realIp = req.headers['x-real-ip'] as string || '0.0.0.0'console.log('Middleware executed, IP:', realIp)console.log('Middleware enter', this.ClsService.als.getStore())this.ClsService.als.run({ ip: realIp }, () => {next()setTimeout(() => {console.log('Middleware timeout', this.ClsService.als.getStore())}, 10)console.log('Middleware exit 1', this.ClsService.als.getStore())})console.log('Middleware exit', this.ClsService.als.getStore())}
}// 模拟拦截器
@Injectable()
class LoggingInterceptor implements NestInterceptor {constructor(private ClsService: ClsService) {console.log('Interceptor registry')}intercept(context: ExecutionContext, next: CallHandler): Observable<any> {console.log('Interceptor executed')return next.handle().pipe(tap((result) => {let req = context.switchToHttp().getRequest() as Requestlet res = context.switchToHttp().getResponse()let cl = (res as Response).get("content-length")console.log("sync===", cl, res.get("content-length"), res.headersSent, result)setTimeout(() => {console.log("===async===", cl, res.get("content-length"), res.headersSent, result)}, 0)}),catchError((error) => {// console.log("interceptor", error)return throwError(() => error)}),finalize(() => {// console.log("entry finalize===")}))}
}// 模拟控制器
@Controller('example')
class ExampleController {constructor() { }@Get("")test() {console.log('Controller method executed')return { message: 'this is nest return' }}@Get("express")express(@Req() req: Request,@Res() res: Response) {console.log('Controller method executed')res.send({message: "this is express send"})}@Get("/stream")getExample(@Req() req: Request,@Res() res: Response) {console.log('Controller method executed')let i = 1res.contentType("application/octet-stream")setInterval(() => {res.write(Buffer.from("abcdefg"))if (i++ > 10) {// stream.close()res.end()}}, 1000)}
}// 应用模块
@Module({imports: [],controllers: [ExampleController],providers: [ClsService,{provide: APP_INTERCEPTOR,useClass: LoggingInterceptor,},],
})
export class AppModule implements NestModule {configure(consumer: MiddlewareConsumer) {consumer.apply(ClsMiddleWare).forRoutes('*') // 应用到所有路由}
}// 启动应用
async function bootstrap() {const app = await NestFactory.create(AppModule)await app.listen(3000)
}bootstrap()

此时访问:http://localhost:3000/example

此时控制台输出的内容为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== undefined undefined false { message: 'this is nest return' }
===async=== undefined 33 true { message: 'this is nest return' }
Middleware timeout { ip: '0.0.0.0' }

这里可以得到4个信息

  • 在宏任务0的异步阶段响应头已经发送
  • 在未发送时是无法获取content-length的,发送后可获取到
  • get(“content-length”)获取的是快照
  • 无论在哪个阶段,使用return的方式返回的数据在interceptor中是可以获取的

接下来访问:http://localhost:3000/example/express

此时控制台输出的内容为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== 34 34 true undefined
===async=== 34 34 true undefined
Middleware timeout { ip: '0.0.0.0' }

可以看到直接send的情况,同步时已经将响应发送完毕了,此时同步异步都可以拿到headers


接下来访问:http://localhost:3000/example/stream

此时控制台输出的内容为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== undefined undefined false undefined
===async=== undefined undefined false undefined
Middleware timeout { ip: '0.0.0.0' }

可以看到直接send的情况,无论是同步还是延时0的宏任务都是拿不到数据的

此时在interceptor中增加:

  res.on("finish", () => {console.log("===response finished", cl, res.get("content-length"), res.headersSent, result)})

此时的控制台输出为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== undefined undefined false undefined
===async=== undefined undefined false undefined
Middleware timeout { ip: '0.0.0.0' }
===response finished undefined undefined true undefined

可以看到面对数据流的情况,即使是发送完成也无法获取到content-length 这种情况目前可以暂不考虑。


目前得到的结论是,如果想稳定拿到contentLength,最好是监听finish事件,即

   res.on("finish", () => {console.log("===response finished", res.get("content-length"))})// 可以优化为:res.once("finish", () => {console.log("===response finished", res.get("content-length"))})

鉴于闭包的形式可能引起的内存泄漏的问题,所以最终采用计算result的方式

  let res = context.switchToHttp().getResponse()let contentLength = res.get("content-length")if (!contentLength && result) {try {contentLength = Buffer.from(JSON.stringify(result)).length ?? 0} catch (error) {contentLength ??= 0}}

这篇关于nest中获取content-length的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1097393

相关文章

C#如何在Excel文档中获取分页信息

《C#如何在Excel文档中获取分页信息》在日常工作中,我们经常需要处理大量的Excel数据,本文将深入探讨如何利用Spire.XLSfor.NET,高效准确地获取Excel文档中的分页信息,包括水平... 目录理解Excel中的分页机制借助 Spire.XLS for .NET 获取分页信息为什么选择 S

springboot3.x使用@NacosValue无法获取配置信息的解决过程

《springboot3.x使用@NacosValue无法获取配置信息的解决过程》在SpringBoot3.x中升级Nacos依赖后,使用@NacosValue无法动态获取配置,通过引入SpringC... 目录一、python问题描述二、解决方案总结一、问题描述springboot从2android.x

springboot的controller中如何获取applicatim.yml的配置值

《springboot的controller中如何获取applicatim.yml的配置值》本文介绍了在SpringBoot的Controller中获取application.yml配置值的四种方式,... 目录1. 使用@Value注解(最常用)application.yml 配置Controller 中

golang实现nacos获取配置和服务注册-支持集群详解

《golang实现nacos获取配置和服务注册-支持集群详解》文章介绍了如何在Go语言中使用Nacos获取配置和服务注册,支持集群初始化,客户端结构体中的IpAddresses可以配置多个地址,新客户... 目录golang nacos获取配置和服务注册-支持集群初始化客户端可选参数配置new一个客户端 支

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

Java发送SNMP至交换机获取交换机状态实现方式

《Java发送SNMP至交换机获取交换机状态实现方式》文章介绍使用SNMP4J库(2.7.0)通过RCF1213-MIB协议获取交换机单/多路状态,需开启SNMP支持,重点对比SNMPv1、v2c、v... 目录交换机协议SNMP库获取交换机单路状态获取交换机多路状态总结交换机协议这里使用的交换机协议为常

MyBatis/MyBatis-Plus同事务循环调用存储过程获取主键重复问题分析及解决

《MyBatis/MyBatis-Plus同事务循环调用存储过程获取主键重复问题分析及解决》MyBatis默认开启一级缓存,同一事务中循环调用查询方法时会重复使用缓存数据,导致获取的序列主键值均为1,... 目录问题原因解决办法如果是存储过程总结问题myBATis有如下代码获取序列作为主键IdMappe

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

Spring Boot中获取IOC容器的多种方式

《SpringBoot中获取IOC容器的多种方式》本文主要介绍了SpringBoot中获取IOC容器的多种方式,包括直接注入、实现ApplicationContextAware接口、通过Spring... 目录1. 直接注入ApplicationContext2. 实现ApplicationContextA

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下