身为前端的你想学后端吗?来学Nest吧[四]

这是我参与11月更文挑战的第17天,活动详情查看:2021最后一次更文挑战

日志

Nest附带一个默认的内部日志记录器实现,它在实例化过程中以及在一些不同的情况下使用,比如发生异常等等(例如系统记录)。这由@nestjs/common包中的Logger类实现。你可以全面控制如下的日志系统的行为

  • 完全禁用日志
  • 指定日志系统详细水平(例如,展示错误,警告,调试信息等)
  • 完全覆盖默认日志记录器
  • 通过扩展自定义默认日志记录器
  • 使用依赖注入来简化编写和测试你的应用
import { LoggerService } from '@nestjs/common';

export class MyLogger implements LoggerService {
  log(message: string) {
    /* your implementation */
  }
  error(message: string, trace: string) {
    /* your implementation */
  }
  warn(message: string) {
    /* your implementation */
  }
  debug(message: string) {
    /* your implementation */
  }
  verbose(message: string) {
    /* your implementation */
  }
}
复制代码

依赖注入Logger

import { Module } from '@nestjs/common';
import { MyLogger } from './my-logger.service';

@Module({
  providers: [MyLogger],
  exports: [MyLogger],
})
export class LoggerModule {}

const app = await NestFactory.create(AppModule);
app.useLogger(app.get(MyLogger));
await app.listen(3000);
复制代码

压缩

npm i --save compression

import * as compression from 'compression';
// somewhere in your initialization file
app.use(compression());
复制代码

上传文件

单文件

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file) {
  console.log(file);
}
复制代码

FileInterceptor接受两个参数

  1. fieldName:指向包含文件的 HTML 表单的字段
  2. multer对象

文件数组

@Post('upload')
@UseInterceptors(FilesInterceptor('files'))
uploadFile(@UploadedFiles() files) {
  console.log(files);
}
复制代码

FilesInterceptor 接收3个参数

  1. fieldName:(保持不变)
  2. maxCount:可选的数字,定义要接受的最大文件数
  3. options:可选的 MulterOptions 对象 ,如上所述

多个文件

@Post('upload')
@UseInterceptors(FileFieldsInterceptor([
  { name: 'avatar', maxCount: 1 },
  { name: 'background', maxCount: 1 },
]))
uploadFile(@UploadedFiles() files) {
  console.log(files);
}
复制代码

要上传多个文件(全部使用不同的键),请使用 FileFieldsInterceptor() 装饰器。这个装饰器有两个参数:

uploadedFields:对象数组,其中每个对象指定一个必需的 name 属性和一个指定字段名的字符串值(如上所述),以及一个可选的 maxCount 属性(如上所述)

options:可选的 MulterOptions 对象,如上所述

任何文件

结语

下一节是数据库,我用的是很少人用的一个orm框架(prisma)

おすすめ

転載: juejin.im/post/7031484327028326436