增加日志Log4js,Swagger,拦截,管道验证,文件上传

master
expressgy 2 years ago
commit 14ba1298e3
  1. 25
      .eslintrc.js
  2. 35
      .gitignore
  3. 5
      .prettierrc
  4. 73
      README.md
  5. 8
      nest-cli.json
  6. 77
      package.json
  7. 5336
      pnpm-lock.yaml
  8. 8
      src/Logger/logger.module.ts
  9. 18
      src/Logger/logger.service.spec.ts
  10. 84
      src/Logger/logger.service.ts
  11. 10
      src/app.module.ts
  12. 48
      src/main.ts
  13. 1
      src/starlight/dto/create-starlight.dto.ts
  14. 25
      src/starlight/dto/defaultTest.dto.ts
  15. 3
      src/starlight/dto/update-starlight.dto.ts
  16. 1
      src/starlight/entities/starlight.entity.ts
  17. 20
      src/starlight/starlight.controller.spec.ts
  18. 51
      src/starlight/starlight.controller.ts
  19. 7
      src/starlight/starlight.guard.spec.ts
  20. 27
      src/starlight/starlight.guard.ts
  21. 9
      src/starlight/starlight.module.ts
  22. 18
      src/starlight/starlight.service.spec.ts
  23. 26
      src/starlight/starlight.service.ts
  24. 24
      test/app.e2e-spec.ts
  25. 9
      test/jest-e2e.json
  26. 4
      tsconfig.build.json
  27. 21
      tsconfig.json

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

35
.gitignore vendored

@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 4
}

@ -0,0 +1,73 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ pnpm install
```
## Running the app
```bash
# development
$ pnpm run start
# watch mode
$ pnpm run start:dev
# production mode
$ pnpm run start:prod
```
## Test
```bash
# unit tests
$ pnpm run test
# e2e tests
$ pnpm run test:e2e
# test coverage
$ pnpm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

@ -0,0 +1,77 @@
{
"name": "tune",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@fastify/multipart": "^7.4.2",
"@fastify/static": "^6.9.0",
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/platform-fastify": "^9.3.9",
"@nestjs/swagger": "^6.2.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"fastify-swagger": "^5.2.0",
"log4js": "^6.9.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "29.2.4",
"@types/node": "18.11.18",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "29.3.1",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "29.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.1",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';
@Module({
providers: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {}

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { LoggerService } from './logger.service';
describe('LoggerService', () => {
let service: LoggerService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [LoggerService],
}).compile();
service = module.get<LoggerService>(LoggerService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

@ -0,0 +1,84 @@
import { ConsoleLogger } from '@nestjs/common';
import { Logger as log4jsLogger, configure, getLogger } from 'log4js';
export class LoggerService extends ConsoleLogger {
defaultLog: log4jsLogger;
fileLog: log4jsLogger;
constructor(logsDir: string) {
super();
configure({
appenders: {
default: {
type: 'console',
layout: {
type: 'pattern',
pattern: `%[%d{yyMMdd-hh:mm:ss:SSS} [%p]\t%m%]`,
},
},
file: {
filename: `${logsDir}/nestjs.services.log`,
type: 'dateFile',
// 配置 layout,此处使用自定义模式 pattern
layout: {
type: 'pattern',
pattern: '%d{yyMMdd-hh:mm:ss:SSS} [%p]\t%m',
},
// 日志文件按日期(天)切割
pattern: 'yy-MM-dd',
// 回滚旧的日志文件时,保证以 .log 结尾 (只有在 alwaysIncludePattern 为 false 生效)
keepFileExt: true,
// 输出的日志文件名是都始终包含 pattern 日期结尾
alwaysIncludePattern: true,
// 指定日志保留的天数
// daysToKeep: 10,
},
},
categories: {
default: {
appenders: ['default'],
level: 'all',
enableCallStack: true,
},
fileAll: {
appenders: ['file'],
level: 'all',
enableCallStack: true,
},
},
});
this.defaultLog = getLogger();
this.fileLog = getLogger('fileAll');
}
log(...arg: any[]) {
// super.log(message, optionalParams);
this.defaultLog.info(arg.join(' '));
this.fileLog.info(arg.join(' '));
}
error(...arg: any[]) {
// super.error(message, trace);
this.defaultLog.error(arg.join(' '));
this.fileLog.error(arg.join(' '));
}
warn(...arg: any[]) {
// super.warn(message, trace);
this.defaultLog.warn(arg.join(' '));
this.fileLog.warn(arg.join(' '));
}
debug(...arg: any[]) {
// super.debug(message, trace);
this.defaultLog.debug(arg.join(' '));
this.fileLog.debug(arg.join(' '));
}
verbose(...arg: any[]) {
// super.verbose(message, trace);
this.defaultLog.info(arg.join(' '));
this.fileLog.info(arg.join(' '));
}
}

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { StarlightModule } from './starlight/starlight.module';
import { LoggerModule } from './logger/logger.module';
@Module({
imports: [StarlightModule, LoggerModule],
controllers: [],
providers: [],
})
export class AppModule {}

@ -0,0 +1,48 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { ValidationPipe } from '@nestjs/common';
import fastifyMultipart from '@fastify/multipart';
import { LoggerService } from './logger/logger.service';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
// 加载主程序模块
AppModule,
// 使用Fastify作为底层框架
new FastifyAdapter({
logger: false,
}),
);
// 日志 Log为文件路径
const logger = new LoggerService('Log');
app.useLogger(logger);
// 全局路由前缀
app.setGlobalPrefix('api');
// 全局开启参数验证--
// 需要安装class-validator 又依赖 class-transformer
app.useGlobalPipes(new ValidationPipe());
// 文件上传中间件
await app.register(fastifyMultipart);
// Swagger
const config = new DocumentBuilder()
.setTitle('Vue Admin Plus 管理系统接口文档')
.setDescription('这是一份关于 Vue Admin Plus 管理系统的接口文档')
.setVersion('1.0.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
await app.listen(3000, '0.0.0.0');
logger.log(`设置应用程序端口号:3000`, 'bootstrap');
logger.log(`应用程序接口地址: http://localhost:3000/api`, 'bootstrap');
logger.log(`应用程序文档地址: http://localhost:3000/docs`, 'bootstrap');
logger.log('🚀 服务应用已经成功启动!', 'bootstrap');
}
bootstrap();

@ -0,0 +1 @@
export class CreateStarlightDto {}

@ -0,0 +1,25 @@
import { IsEmail, IsNotEmpty, IsPhoneNumber, IsString } from 'class-validator';
// 此文件为参数验证演示
// https://github.com/typestack/class-validator#usage
// 这里有更多的验证方法
export class CreateXiaomanDto {
@IsNotEmpty({
message: 'name 不能为空',
})
@IsString()
name: string;
@IsPhoneNumber('CN', {
message: 'phone 不是一个电话号码',
})
phone: string;
@IsEmail(
{},
{
message: 'email 不是一个合法邮箱',
},
)
email: string;
}

@ -0,0 +1,3 @@
import { CreateStarlightDto } from './create-starlight.dto';
export class UpdateStarlightDto {}

@ -0,0 +1 @@
export class Starlight {}

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { StarlightController } from './starlight.controller';
import { StarlightService } from './starlight.service';
describe('StarlightController', () => {
let controller: StarlightController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [StarlightController],
providers: [StarlightService],
}).compile();
controller = module.get<StarlightController>(StarlightController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

@ -0,0 +1,51 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
UseGuards,
} from '@nestjs/common';
import { StarlightService } from './starlight.service';
import { CreateStarlightDto } from './dto/create-starlight.dto';
import { UpdateStarlightDto } from './dto/update-starlight.dto';
import { StarlightGuard } from './starlight.guard';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('starlight')
@Controller('starlight')
// 拦截器
@UseGuards(StarlightGuard)
export class StarlightController {
constructor(private readonly starlightService: StarlightService) {}
@Post()
create(@Body() createStarlightDto: CreateStarlightDto) {
return this.starlightService.create(createStarlightDto);
}
@Get()
findAll() {
return this.starlightService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.starlightService.findOne(+id);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() updateStarlightDto: UpdateStarlightDto,
) {
return this.starlightService.update(+id, updateStarlightDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.starlightService.remove(+id);
}
}

@ -0,0 +1,7 @@
import { StarlightGuard } from './starlight.guard';
describe('StarlightGuard', () => {
it('should be defined', () => {
expect(new StarlightGuard()).toBeDefined();
});
});

@ -0,0 +1,27 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
// 此文件为拦截器
@Injectable()
export class StarlightGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
console.log(context);
const request = context.switchToHttp().getRequest();
// console.log(request);
console.log(request.url);
console.log(request.headers);
// 自定义返回消息
throw new UnauthorizedException({
statusCode: 403,
message: '你没有访问权限',
error: 'Forbidden',
});
return false;
}
}

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { StarlightService } from './starlight.service';
import { StarlightController } from './starlight.controller';
@Module({
controllers: [StarlightController],
providers: [StarlightService],
})
export class StarlightModule {}

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { StarlightService } from './starlight.service';
describe('StarlightService', () => {
let service: StarlightService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [StarlightService],
}).compile();
service = module.get<StarlightService>(StarlightService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { CreateStarlightDto } from './dto/create-starlight.dto';
import { UpdateStarlightDto } from './dto/update-starlight.dto';
@Injectable()
export class StarlightService {
create(createStarlightDto: CreateStarlightDto) {
return 'This action adds a new starlight';
}
findAll() {
return `This action returns all starlight`;
}
findOne(id: number) {
return `This action returns a #${id} starlight`;
}
update(id: number, updateStarlightDto: UpdateStarlightDto) {
return `This action updates a #${id} starlight`;
}
remove(id: number) {
return `This action removes a #${id} starlight`;
}
}

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}
Loading…
Cancel
Save