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

相关文章

SpringBoot整合mybatisPlus实现批量插入并获取ID详解

《SpringBoot整合mybatisPlus实现批量插入并获取ID详解》这篇文章主要为大家详细介绍了SpringBoot如何整合mybatisPlus实现批量插入并获取ID,文中的示例代码讲解详细... 目录【1】saveBATch(一万条数据总耗时:2478ms)【2】集合方式foreach(一万条数

python获取网页表格的多种方法汇总

《python获取网页表格的多种方法汇总》我们在网页上看到很多的表格,如果要获取里面的数据或者转化成其他格式,就需要将表格获取下来并进行整理,在Python中,获取网页表格的方法有多种,下面就跟随小编... 目录1. 使用Pandas的read_html2. 使用BeautifulSoup和pandas3.

SpringBoot UserAgentUtils获取用户浏览器的用法

《SpringBootUserAgentUtils获取用户浏览器的用法》UserAgentUtils是于处理用户代理(User-Agent)字符串的工具类,一般用于解析和处理浏览器、操作系统以及设备... 目录介绍效果图依赖封装客户端工具封装IP工具实体类获取设备信息入库介绍UserAgentUtils

C# foreach 循环中获取索引的实现方式

《C#foreach循环中获取索引的实现方式》:本文主要介绍C#foreach循环中获取索引的实现方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、手动维护索引变量二、LINQ Select + 元组解构三、扩展方法封装索引四、使用 for 循环替代

Linux下如何使用C++获取硬件信息

《Linux下如何使用C++获取硬件信息》这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录方法获取CPU信息:读取"/proc/cpuinfo"文件获取磁盘信息:读取"/proc/diskstats"文

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法

《golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法》:本文主要介绍golang获取当前时间、时间戳和时间字符串及它们之间的相互转换,本文通过实例代码给大家介绍的非常详细,感兴趣... 目录1、获取当前时间2、获取当前时间戳3、获取当前时间的字符串格式4、它们之间的相互转化上篇文章给大家介

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,