Commit 6c68b8cf by hometown

feat: init project

parents
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',
},
};
# 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
\ No newline at end of file
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
{
"recommendations": [
// my extensions, ofc :P
"antfu.browse-lite",
"antfu.iconify",
"antfu.slidev",
"antfu.unocss",
"antfu.vite",
"antfu.where-am-i",
"antfu.open-in-github-button",
"lokalise.i18n-ally",
// themes & icons
"antfu.icons-carbon",
"antfu.theme-vitesse",
"file-icons.file-icons",
"sainnhe.gruvbox-material",
// life savers!
"dbaeumer.vscode-eslint",
"Vue.volar",
"GitHub.copilot",
"usernamehw.errorlens",
"streetsidesoftware.code-spell-checker",
// up to you
"eamodio.gitlens",
"EditorConfig.EditorConfig",
"github.vscode-github-actions",
"GitHub.vscode-pull-request-github",
"johnsoncodehk.vscode-tsconfig-helper",
"mpontus.tab-cycle",
"naumovs.color-highlight",
"WakaTime.vscode-wakatime",
"znck.grammarly"
]
}
<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).
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
{
"name": "service-nest",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"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": {
"@nestjs/common": "^7.5.5",
"@nestjs/core": "^7.5.5",
"@nestjs/graphql": "^7.9.1",
"@nestjs/jwt": "^7.2.0",
"@nestjs/passport": "^7.1.5",
"@nestjs/platform-express": "^7.5.5",
"@nestjs/swagger": "^4.7.5",
"@nestjs/typeorm": "^7.1.5",
"apollo-server-express": "^2.19.0",
"bcrypt": "^5.0.0",
"body-parser-xml": "^2.0.1",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"dayjs": "^1.9.7",
"express-rate-limit": "^5.2.3",
"graphql": "^15.4.0",
"graphql-tools": "^7.0.2",
"helmet": "^4.2.0",
"mysql": "^2.18.1",
"nestjs-config": "^1.4.7",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"request-ip": "^2.1.3",
"rimraf": "^3.0.2",
"rxjs": "^6.6.3",
"swagger-ui-express": "^4.1.5",
"typeorm": "^0.2.29"
},
"devDependencies": {
"@nestjs/cli": "^7.5.3",
"@nestjs/schematics": "^7.2.5",
"@nestjs/testing": "^7.5.5",
"@types/express": "^4.17.9",
"@types/jest": "26.0.18",
"@types/node": "^14.14.12",
"@types/passport-jwt": "^3.0.3",
"@types/passport-local": "^1.0.33",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^4.9.1",
"@typescript-eslint/parser": "^4.9.1",
"eslint": "^7.15.0",
"eslint-config-prettier": "^7.0.0",
"eslint-plugin-import": "^2.22.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.0.1",
"ts-jest": "26.4.4",
"ts-loader": "^8.0.11",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.2"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ChatController } from './modules/chat/chat.controller';
import { ChatService } from './modules/chat/chat.service';
import { ChatModule } from './modules/chat/chat.module';
@Module({
imports: [ChatModule],
controllers: [AppController, ChatController],
providers: [AppService, ChatService],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
Logger,
HttpStatus,
} from '@nestjs/common';
import { GqlArgumentsHost } from '@nestjs/graphql';
import * as dayjs from 'dayjs';
// 需要实现 ExceptionFilter 接口,里面有一个catch方法需要实现
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp(); //获取状态信息
const response = ctx.getResponse();
const request = ctx.getRequest()
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const exceptionRes = exception.getResponse() as { error: string, message: string }
if (response?.status) {
const { error, message } = exceptionRes
const errorResponse = {
timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
message: message || exceptionRes,
path: request?.url,
status,
error,
code: 0,
ok: false,
result: {}
}
Logger.error(
`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${request?.method} ${request?.url}`,
JSON.stringify(errorResponse),
'HttpExceptionFilter',
);
response.status(status).json(errorResponse);
} else {
// 单独处理过滤graqhql的异常
const gqlHost = GqlArgumentsHost.create(host);
const httpRequest = this.getRequestFromCtx(ctx)
exception.message = `${exceptionRes.message || ''} ${exceptionRes.error || ''}`
// 异常错误
let request: any = {
graphql: {
args: gqlHost.getArgs(),
root: gqlHost.getRoot(),
},
}
try {
if (httpRequest) {
request = Object.assign(request, {
url: httpRequest.url,
body: httpRequest.body,
query: httpRequest.query,
params: httpRequest.params,
headers: httpRequest.headers,
currentUser: httpRequest.currentUser
})
}
request = JSON.stringify(request)
Logger.error(
`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${exception.message}`,
JSON.stringify(request),
'GraphQLExceptionFilter'
)
} catch {
Logger.error(
`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${exception.message}`,
'处理graqhql异常时',
'GraphQLExceptionFilter'
)
}
return exception;
}
}
getRequestFromCtx(ctx) {
for (let arg of ctx.args) {
if (arg && arg.request && arg.request?.url) {
return arg.request
}
}
}
}
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response } from 'express';
import * as dayjs from "dayjs";
import { isEmpty } from 'class-validator';
@Injectable() // 使用Injectable装饰器
export class LoggerMiddleware implements NestMiddleware { // 使用NestMiddleware实现
use(req: Request, res: Response, next: Function) { // 重写方法
const { method, path, baseUrl } = req;
Logger.log(`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${method} ${baseUrl}`, 'LoggerMiddleware')
// 必须调用next()将控制权传递给下一个中间件功能。否则请求将被挂起
next();
}
}
// 全局监听
export function LoggerGlobal(req: Request, res: Response, next: Function) {
const { method, path } = req;
Logger.log(`[${dayjs().format('YYYY-MM-DD HH:mm:ss')}] ${method} ${path}`, 'LoggerGlobal');
next();
};
import { ArgumentMetadata, HttpException, HttpStatus, Injectable, PipeTransform, Type, } from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) return value;
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
// const errObj = {};
// errors.forEach(err => {
// const {
// property,
// constraints,
// } = err;
// errObj[property] = Object.values(constraints);
// });
const errObj = Object.values(errors[0].constraints)[0];
throw new HttpException(
{ message: '请求参数验证失败 ', error: errObj },
HttpStatus.BAD_REQUEST,
);
}
return value;
}
private toValidate(metatype: Type<any>): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { classToPlain } from 'class-transformer';
import systemConfig from "../config/system";
const transformValue = (result: any, code: number = 0, message: string = '请求成功', ok = true) => {
const { returnFormat } = systemConfig
return {
[returnFormat.result]: classToPlain(result),
[returnFormat.code]: code,
[returnFormat.message]: message,
[returnFormat.ok]: ok,
}
}
// 处理统一成功返回值
@Injectable()
export class TransformReturnInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const host = context.switchToHttp();
const request = host.getRequest();
// 不需要格式化的接口
if (['/api/status'].includes(request?.url)) {
return next.handle();
}
return next.handle().pipe(map(transformValue))
}
}
const system = {
adminPath: 'admin', // 管理员路径
staticPrefixPath: '', // 静态文件的前缀
supportImgTypes: ['.png', '.jpg', '.gif', '.jpeg'], //支持的图片
defaultAccount: 'admin', // 默认账号
defaultPassword: '123456', // 默认密码
returnFormat: {
result: 'result',
code: 'code',
message: 'message',
ok: 'ok'
}
}
export default system
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { LoggerGlobal } from './common/logger.middleware';
import { ValidationPipe } from './common/pipes/validation.pipe';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as rateLimit from 'express-rate-limit';
import * as requestIp from 'request-ip';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { TransformReturnInterceptor } from './common/transform.return';
const bodyParser = require('body-parser');
require('body-parser-xml')(bodyParser);
const PORT = 3333;
const PREFIX = 'api'
const SWAGGER_V1 = `${PREFIX}/v1/swagger`
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.setGlobalPrefix(PREFIX);
const options = new DocumentBuilder() // 创建并配置文档信息
.setTitle('标题')
.setDescription('描述信息')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
// 会自动将所有路由显示出来
SwaggerModule.setup(SWAGGER_V1, app, document); // api/swagger = API文档的路径,访问:http://localhost:3000/api/swagger
// 跨域资源共享
app.enableCors()
// 限制访问频率
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 500, // 限制15分钟内最多只能访问500次
}),
);
app.use(bodyParser.xml({
limit: '1MB', // 拒绝大于1 MB的有效负载
xmlParseOptions: {
normalize: true, // 在文本节点内修剪空格
normalizeTags: true, // 将标签转换为小写
explicitArray: false // 如果> 1,则仅将节点放入数组
}
}));
// 拦截处理-错误异常
// graphQL专属异常过滤
// app.useGlobalFilters(new GraphQLExceptionFilter());
app.useGlobalFilters(new HttpExceptionFilter());
// 拦截处理-返回格式
app.useGlobalInterceptors(new TransformReturnInterceptor());
// 获取访问者ip地址
app.use(requestIp.mw());
// 全局监听路由请求
app.use(LoggerGlobal);
// 使用管道验证数据
app.useGlobalPipes(new ValidationPipe());
await app.listen(PORT, () => {
Logger.log(`已启动,接口: http://localhost:${PORT}/${PREFIX} , API文档:http://localhost:${PORT}/${SWAGGER_V1}`);
});
}
bootstrap().catch(err => Logger.error('启动错误:', err));
import { Test, TestingModule } from '@nestjs/testing';
import { ChatController } from './chat.controller';
describe('ChatController', () => {
let controller: ChatController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ChatController],
}).compile();
controller = module.get<ChatController>(ChatController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
import { ChatService } from './chat.service';
import { Body, Controller, HttpException, HttpStatus, Post, Req } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { sendMessageDto } from './dto/sendMessage.dto';
@ApiTags('chat')
@Controller('chat')
export class ChatController {
constructor(private readonly chatService: ChatService) {}
@ApiOperation({ summary: '发送消息', description: '向ERNIE Bot模型发送消息得到答案' })
@Post('sendMessage')
sendMessage(@Body() body: sendMessageDto) {
try {
return this.chatService.sendMessage(body.messages)
} catch (error) {
new HttpException({ message: '服务端错误 ', error: error }, HttpStatus.BAD_REQUEST)
}
}
}
import { Module } from '@nestjs/common';
import { ChatController } from './chat.controller';
import { ChatService } from './chat.service';;
@Module({
controllers: [ChatController],
providers: [ChatService],
})
export class ChatModule { }
import { Test, TestingModule } from '@nestjs/testing';
import { ChatService } from './chat.service';
describe('ChatService', () => {
let service: ChatService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChatService],
}).compile();
service = module.get<ChatService>(ChatService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
import { Injectable } from '@nestjs/common';
import type { Message } from './dto/sendMessage.dto';
@Injectable()
export class ChatService {
sendMessage(messages: Message[]) {
return messages
}
}
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, ArrayMinSize } from "class-validator"
export interface Message {
role: 'user' | 'admin'
content: string
}
export class sendMessageDto {
@IsArray({message: '消息数组必须是数组'})
@ArrayMinSize(1, {message: '消息数组长度最小为1'})
@ApiPropertyOptional({ description: '消息数组', example: [{ role: 'user', content: '你好' }] })
public readonly messages: Message[]
}
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!');
});
});
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment