nestjs编程-nestjs装饰器

Nestjs核心模块:

        @nestjs/core

        @nestjs/common:

    装饰器:

        装饰器所在模块:'@nestjs/common';   

        常用装饰器:@Module() @Controller() @Injectable()  @Get() @Post() @Request() @Response()@Next() @Session()@Param()@Body()@Query()@Headers()@HttpCode()

        @Module(): 类装饰器

                可传入一个对象类型的参数

@Module({
  imports: [], // 依赖注入子模块
  controllers: [AppController], // 注入模块控制器
  providers: [AppService], // 注入模块的Service
})
       @Controller(): 类装饰器

                可传入字符串类型参数,对应请求的路由

@Controller({
  path:'user',
  version:'1'
})

        指定当前控制器的路由是'user' ,版本是1,使用的时候是localhost:3000/v1/user

       @Injectable():类装饰器

                用于定义一个类可以被依赖注入(Dependency Injection,DI)。NestJS的DI容器会负责创建和管理该类,在需要该类的地方注入。

export class AppController {
  constructor(private readonly appService: AppService) {}
}

               因为AppService类添加了@Injectable()依赖注入,DI容器会在这里注入。

      @Request(): 参数装饰器

                作用是将参数变为Request对象,然后可以获取请求参数、请求头等信息

      @Query(): 参数装饰器 

                作用是将参数变为请求url的query对象,然后可以获取请求参数。也可以用req.query代替。

 @Get()
  getHello(@Request() req,@Query() qs): string {
    console.log(qs,'qs')
    console.log(req.query,'req')
    return this.appService.getHello();
  }
         @Body('xxx'):参数装饰器 

                主要作用将参数转变为Body对象,直接获取请求体的参数。

                同样可以通过req.body来获取

                通过传参可以直接获取body的属性

 @Post('setHello')
  setHello(@Request() req,@Body('name') body):string{
    console.log(body,'body')
    console.log(req.body,'req')
    return 'post'
  }
             @Get()和 @Post(): 函数装饰器

                    根据Restful协议将控制器的函数映射为GeT或Post请求响应。

                     可传参数,将函数的url变为动态路由

  @Get('getHello/:id')
  getHello(@Request() req,@Query() qs,@Param('id') id): string {
    console.log(qs,'qs')
    console.log(req.query,'req')
    console.log(id,'id')
    return this.appService.getHello();
  }
            @Param(): 参数装饰器   

                        获取动态路由参数,可传参,指定当前restful URL的具体的参数

             @Headers(): 参数装饰器 

                        用于获取请求头,可以用req.headers代替   

 @Post('setHello')
  setHello(@Request() req,@Body('name') body,@Headers() headers):string{
    console.log(req.headers,'req.headers')
    console.log(headers,'headers')
    return 'post'
  }
              @HttpCode(): 函数装饰器

                   作用:控制接口返回的状态码

  @Post('setHello')
  @HttpCode(500)
  setHello(@Request() req,@Body('name') body,@Headers() headers):string{
    console.log(req.headers,'req.headers')
    console.log(headers,'headers')
    return 'post'
  }
  总结: 

       1. 装饰器能够提供编码的便捷,部分装饰器可以不用,Request和Response直接获取也没问题,装饰器主打一个方面

        2. 学习装饰器前,最好先学习下装饰器的基本原理

                

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NestJS Cache Manager is a module for caching data in NestJS applications. It provides a simple interface for caching data using various caching strategies such as memory, Redis, and others. Redis is one of the caching strategies that NestJS Cache Manager supports. Redis is an in-memory data structure store that can be used as a database, cache, and message broker. It is often used as a cache because of its high performance and scalability. Redis stores data in memory, which makes it faster than traditional disk-based databases. Using Redis as a caching strategy in NestJS Cache Manager is easy. First, you need to install the Redis module: ``` npm install cache-manager-redis-store ``` Next, you need to configure the Redis cache in your NestJS application: ``` import { CacheModule, Module } from '@nestjs/common'; import * as redisStore from 'cache-manager-redis-store'; @Module({ imports: [ CacheModule.register({ store: redisStore, host: 'localhost', port: 6379, }), ], }) export class AppModule {} ``` In this example, we import the CacheModule and configure it to use the Redis store. We set the host and port to connect to the Redis instance. Now, you can use the cache in your NestJS application: ``` import { CacheInterceptor, CacheTTL, Controller, Get, UseInterceptors } from '@nestjs/common'; @Controller('cats') export class CatsController { @Get() @UseInterceptors(CacheInterceptor) @CacheTTL(60) findAll(): string[] { return ['Cat 1', 'Cat 2', 'Cat 3']; } } ``` In this example, we use the CacheInterceptor to cache the response of the findAll() method for 60 seconds. This means that subsequent requests for the same resource will be served from the cache, which improves performance and reduces the load on the server. Overall, using Redis as a caching strategy in NestJS Cache Manager is a great way to improve the performance and scalability of your NestJS application.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值