0.0.19 • Published 6 years ago

g-modules v0.0.19

Weekly downloads
-
License
MIT
Repository
-
Last release
6 years ago

G Basic Nest Node_Modules

Install

npm install g-modules

Test

npm run test

查看测试覆盖率

npm run test:cov

日志使用

  • 在main.ts头部引用并初始化
import {Logger} from 'g-modules' 
new Logger('Demo测试') //input your Service Name 

所有的日志文件会生成在src/logs目录下面

  • 全局引用中间件LogInputMiddleware 该中间件有两个功能:
    在请求上下文中,给req添加logger属性,开发人员可以通过req.logger来输出日志
    在每个请求中,打印请求路由&&请求参数日志,方便后续查找问题
    日志目录: /logs
    日志格式结构:
interface FormatOptions {
    message: string;
    level: string;
    label: string;
    timestamp: string;
    module?: string;
    requestId?: string;
    error?: Error;
}

用法如下:
在app.module.ts中AppModule添加配置信息

import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import {LogInputMiddleware} from 'g-modules' 
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LogInputMiddleware)
      .forRoutes({    
        path: '*',
        method: RequestMethod.ALL,  // 针对所有路由
      });
  }
}

在后续的路由请求中,可以调用 req.logger中的如下四个方法

   * info(message:string,options?: IOptions)  
   * debug(message:string,options?: IOptions)  
   * warn(message:string,options?: IOptions)  
   * error(message:Error,options?: IOptions)  

IOptions结构为:

interface IOptions {
 module?: string;  //模块名
 requestId?: string;  //请求id
}

G错误类

Nest.js有内置的错误类供开发人员使用,具体请看 但是对于企业来说,这些远远不够,所以G提供了GaiaException额外的一些错误定义。具体实现如下:

export class GaiaException extends Error {
    statusCode: number;
    constructor(code: number, msg?: any) {
        super();
        this.statusCode = code;
        this.message = msg || errMsg[code];
    }
}

export enum GaiaErrorCode {
    ParamsError = 10001,
    RoleError = 10002,
}

const errMsg = {
    10001: 'Param Error',
    10002: 'Role Error',
};

后续如需添加,请联系组件库成员添加。
具体使用方法:

import { GaiaException,GaiaErrorCode } from 'g-modules';
throw new GaiaException(GaiaErrorCode.RoleError);
//或者 自定义消息
throw new GaiaException(GaiaErrorCode.ParamsError, 'some errors');

用户角色认证(看守器)

此组件用于判定请求路由是否有权限进行访问,是根据header中的roles字段判断的
用法:

  • 在需要添加角色认证的模块(.module.ts)文件中添加:
import { RolesGuard } from 'g-modules';
import { APP_GUARD } from '@nestjs/core';
@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: RolesGuard,
    },
  ],
})
  • 在路由前面添加装饰器 @SetMetadata,例如:
    @Post('/create')
    @SetMetadata('roles', ['admin']) // 第一个参数代表取的角色字段,第二个参数代表该路由允许访问的角色数组
    async create(@Body() userDto: UserDto) {
        const result = this.usersService.create(userDto);
        return result;
    }

异常过滤器(filter)

此组件用于过滤错误,并且记录错误日志以及统一能获取到上下文的错误(有req,res)的返回格式:

{
      statusCode: number,
      message: string,
      time: new Date(),
      path: request.url || '',
}
// Example:
{
    "statusCode": 10002,
    "message": "Role Error",
    "time": "2019-06-27T01:42:09.282Z",
    "path": "/user/create"
}

使用方式(在main.ts中全局添加):

import { AllExceptionsFilter } from 'g-modules';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new AllExceptionsFilter()); //全局添加
  await app.listen(3000, () => {});
}

拦截器(interceptor)

  • 请求时间记录
    该组件如名字所示,会记录该次业务处理的时间,如接口相应时间超过200ms,则以warn形式打印日志,需要优化,使用方式(main.ts全局引用):
import { RequestTimeInterceptor } from 'g-modules';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalInterceptors(new RequestTimeInterceptor()//全局添加
  await app.listen(3000, () => {});
}
  • 请求返回数据格式统一
    现实开发过程中,我们需要统一正确的返回值格式,运用此拦截器可使返回值格式为:
{
   statusCode: 200,
   data: any,
   time: new Date()
}

使用方式:

import { TransformInterceptor } from 'g-modules';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalInterceptors(new TransformInterceptor()//全局添加
  await app.listen(3000, () => {});
}

注意:因为graphql的请求返回格式是自定义的,所以该拦截器不会统一graphql的接口返回格式

参数验证(pipe)

日常开发中,前后端往往会定义接口的入参结构,该组件用于验证前端的传入参数。如若多传会被pass(安全性),如若少传或者结构类型错误,都会返回错误。 用法如下(main.ts全局引用):

import { ValidationPipe } from 'g-modules';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());//全局添加
  await app.listen(3000, () => {});
}

注意: 此组件是配合class-validator用的,具体用法可去github查看

0.0.19

6 years ago

0.0.18

6 years ago

0.0.17

6 years ago

0.0.16

6 years ago

0.0.15

6 years ago

0.0.14

6 years ago

0.0.13

6 years ago

0.0.12

6 years ago

0.0.11

6 years ago

0.0.10

6 years ago

0.0.9

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago