feat: init project.
This commit is contained in:
commit
7b715e807f
73
README.md
Normal file
73
README.md
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" 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
|
||||||
|
$ npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running the app
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm 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).
|
18
config.yml.example
Normal file
18
config.yml.example
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
env: dev
|
||||||
|
http:
|
||||||
|
port: 7132
|
||||||
|
|
||||||
|
db:
|
||||||
|
postgres:
|
||||||
|
host: 192.168.31.194
|
||||||
|
port: 5432
|
||||||
|
database: blog
|
||||||
|
username: blog
|
||||||
|
password:
|
||||||
|
redis:
|
||||||
|
host: 192.168.31.194
|
||||||
|
port: 6379
|
||||||
|
password:
|
||||||
|
prefix: blog
|
||||||
|
workspaces:
|
||||||
|
root: '/Users/ivanli/Projects/fennec/workspaces'
|
33
docs/ci-cd.md
Normal file
33
docs/ci-cd.md
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
# CI/CD 流程
|
||||||
|
0. 准备
|
||||||
|
- project information
|
||||||
|
- commit hash
|
||||||
|
1. checkout
|
||||||
|
2. install dependencies
|
||||||
|
3. run test script
|
||||||
|
5. run deploy script
|
||||||
|
6. clear workspace
|
||||||
|
|
||||||
|
## 流水线任务单元描述
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"unit": {
|
||||||
|
"install-dependencies": {
|
||||||
|
"script": "npm ci"
|
||||||
|
},
|
||||||
|
"test": {
|
||||||
|
"script": "npm test"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"script": "npm build"
|
||||||
|
},
|
||||||
|
"deploy": {
|
||||||
|
"script": [
|
||||||
|
"npm build"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
10
docs/development-notes.md
Normal file
10
docs/development-notes.md
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
# Fennec CI/CD 工具开发手记
|
||||||
|
## 前言
|
||||||
|
这是 Fennec 后端项目开发手记,用于记录开发过程中遇到的知识点、难点、思路和解决方案。
|
||||||
|
|
||||||
|
## Git Repository 操作
|
||||||
|
### 获取 git 远程仓库信息流程
|
||||||
|
1. `git init` // 初始化一个本地 git 仓库。
|
||||||
|
2. `git remote add <name> <address>` // 添加远程仓库
|
||||||
|
3. `git fetch` // 获取远程仓库信息
|
||||||
|
|
8
nest-cli.json
Normal file
8
nest-cli.json
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"plugins": ["@nestjs/graphql"],
|
||||||
|
"introspectComments": true
|
||||||
|
}
|
||||||
|
}
|
13020
package-lock.json
generated
Normal file
13020
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
95
package.json
Normal file
95
package.json
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
{
|
||||||
|
"name": "fennec-be",
|
||||||
|
"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": "DEBUG=fennec:* nest start --watch",
|
||||||
|
"start:debug": "DEBUG=fennec:* 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/bull": "^0.3.1",
|
||||||
|
"@nestjs/common": "^7.5.1",
|
||||||
|
"@nestjs/config": "^0.6.2",
|
||||||
|
"@nestjs/core": "^7.5.1",
|
||||||
|
"@nestjs/graphql": "^7.9.8",
|
||||||
|
"@nestjs/platform-express": "^7.5.1",
|
||||||
|
"@nestjs/typeorm": "^7.1.5",
|
||||||
|
"@types/bull": "^3.15.0",
|
||||||
|
"apollo-server-express": "^2.19.2",
|
||||||
|
"bcrypt": "^5.0.0",
|
||||||
|
"body-parser": "^1.19.0",
|
||||||
|
"bull": "^3.20.1",
|
||||||
|
"class-transformer": "^0.3.2",
|
||||||
|
"class-validator": "^0.13.1",
|
||||||
|
"debug": "^4.3.1",
|
||||||
|
"graphql": "^15.5.0",
|
||||||
|
"graphql-tools": "^7.0.2",
|
||||||
|
"ioredis": "^4.25.0",
|
||||||
|
"js-yaml": "^4.0.0",
|
||||||
|
"nestjs-redis": "^1.2.8",
|
||||||
|
"observable-to-async-generator": "^1.0.1-rc",
|
||||||
|
"pg": "^8.5.1",
|
||||||
|
"ramda": "^0.27.1",
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"rxjs": "^6.6.3",
|
||||||
|
"simple-git": "^2.35.0",
|
||||||
|
"typeorm": "^0.2.30"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@nestjs/cli": "^7.5.7",
|
||||||
|
"@nestjs/schematics": "^7.1.3",
|
||||||
|
"@nestjs/testing": "^7.5.1",
|
||||||
|
"@types/body-parser": "^1.19.0",
|
||||||
|
"@types/debug": "^4.1.5",
|
||||||
|
"@types/express": "^4.17.8",
|
||||||
|
"@types/ioredis": "^4.22.3",
|
||||||
|
"@types/jest": "^26.0.15",
|
||||||
|
"@types/node": "^14.14.6",
|
||||||
|
"@types/supertest": "^2.0.10",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^4.6.1",
|
||||||
|
"@typescript-eslint/parser": "^4.6.1",
|
||||||
|
"eslint": "^7.12.1",
|
||||||
|
"eslint-config-prettier": "7.2.0",
|
||||||
|
"eslint-plugin-prettier": "^3.1.4",
|
||||||
|
"jest": "^26.6.3",
|
||||||
|
"prettier": "^2.1.2",
|
||||||
|
"supertest": "^6.0.0",
|
||||||
|
"ts-jest": "^26.4.3",
|
||||||
|
"ts-loader": "^8.0.8",
|
||||||
|
"ts-node": "^9.0.0",
|
||||||
|
"tsconfig-paths": "^3.9.0",
|
||||||
|
"typescript": "^4.0.5"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
|
}
|
22
src/app.controller.spec.ts
Normal file
22
src/app.controller.spec.ts
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
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!');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
12
src/app.controller.ts
Normal file
12
src/app.controller.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
83
src/app.module.ts
Normal file
83
src/app.module.ts
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { GraphQLModule } from '@nestjs/graphql';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { AppController } from './app.controller';
|
||||||
|
import { AppResolver } from './app.resolver';
|
||||||
|
import { AppService } from './app.service';
|
||||||
|
import configuration from './commons/config/configuration';
|
||||||
|
import { RedisModule } from 'nestjs-redis';
|
||||||
|
import { ParseBodyMiddleware } from './commons/middleware/parse-body.middleware';
|
||||||
|
import { BullModule } from '@nestjs/bull';
|
||||||
|
import { PubSubModule } from './commons/pub-sub/pub-sub.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
load: [configuration],
|
||||||
|
}),
|
||||||
|
TypeOrmModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
type: 'postgres',
|
||||||
|
host: configService.get<string>('db.postgres.host'),
|
||||||
|
port: configService.get<number>('db.postgres.port'),
|
||||||
|
username: configService.get<string>('db.postgres.username'),
|
||||||
|
password: configService.get<string>('db.postgres.password'),
|
||||||
|
database: configService.get<string>('db.postgres.database'),
|
||||||
|
synchronize: true,
|
||||||
|
autoLoadEntities: true,
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
GraphQLModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
debug: configService.get<string>('env') !== 'prod',
|
||||||
|
playground: true,
|
||||||
|
autoSchemaFile: true,
|
||||||
|
installSubscriptionHandlers: true,
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
BullModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
redis: {
|
||||||
|
host: configService.get<string>('db.redis.host', 'localhost'),
|
||||||
|
port: configService.get<number>('db.redis.port', undefined),
|
||||||
|
password: configService.get<string>('db.redis.password', undefined),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
PubSubModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
redis: {
|
||||||
|
host: configService.get<string>('db.redis.host', 'localhost'),
|
||||||
|
port: configService.get<number>('db.redis.port', undefined),
|
||||||
|
password: configService.get<string>('db.redis.password', undefined),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
RedisModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
host: configService.get<string>('db.redis.host', 'localhost'),
|
||||||
|
port: configService.get<number>('db.redis.port', 6379),
|
||||||
|
password: configService.get<string>('db.redis.password', ''),
|
||||||
|
keyPrefix: configService.get<string>('db.redis.prefix', 'blog') + ':',
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [AppController],
|
||||||
|
providers: [AppService, AppResolver],
|
||||||
|
})
|
||||||
|
export class AppModule implements NestModule {
|
||||||
|
public configure(consumer: MiddlewareConsumer): void {
|
||||||
|
consumer.apply(ParseBodyMiddleware).forRoutes('*');
|
||||||
|
}
|
||||||
|
}
|
10
src/app.resolver.ts
Normal file
10
src/app.resolver.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { Query, Resolver } from '@nestjs/graphql';
|
||||||
|
import { Hello } from './hello';
|
||||||
|
|
||||||
|
@Resolver(() => Hello)
|
||||||
|
export class AppResolver {
|
||||||
|
@Query(() => Hello)
|
||||||
|
async hello() {
|
||||||
|
return { message: 'Hello, World!' };
|
||||||
|
}
|
||||||
|
}
|
8
src/app.service.ts
Normal file
8
src/app.service.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AppService {
|
||||||
|
getHello(): string {
|
||||||
|
return 'Hello World!';
|
||||||
|
}
|
||||||
|
}
|
10
src/commons/commons.module.ts
Normal file
10
src/commons/commons.module.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PasswordConverter } from './services/password-converter';
|
||||||
|
import { PubSubModule } from './pub-sub/pub-sub.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [PasswordConverter],
|
||||||
|
exports: [PasswordConverter],
|
||||||
|
imports: [PubSubModule],
|
||||||
|
})
|
||||||
|
export class CommonsModule {}
|
9
src/commons/config/configuration.ts
Normal file
9
src/commons/config/configuration.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import { readFileSync } from 'fs';
|
||||||
|
import * as yaml from 'js-yaml';
|
||||||
|
import { join } from 'path';
|
||||||
|
|
||||||
|
export default () => {
|
||||||
|
return yaml.load(
|
||||||
|
readFileSync(join(__dirname, '../../../config.yml'), 'utf8'),
|
||||||
|
) as unknown;
|
||||||
|
};
|
23
src/commons/entities/app-base-entity.ts
Normal file
23
src/commons/entities/app-base-entity.ts
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||||
|
import {
|
||||||
|
CreateDateColumn,
|
||||||
|
DeleteDateColumn,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class AppBaseEntity {
|
||||||
|
@Field(() => ID)
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ select: false })
|
||||||
|
updatedAt: Date;
|
||||||
|
|
||||||
|
@DeleteDateColumn({ select: false })
|
||||||
|
deletedAt?: Date;
|
||||||
|
}
|
6
src/commons/exceptions/Insufficient-balance.exception.ts
Normal file
6
src/commons/exceptions/Insufficient-balance.exception.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export class InsufficientBalanceException extends Error {
|
||||||
|
constructor(curr: number, amount: number) {
|
||||||
|
super();
|
||||||
|
this.message = `余额不足。current balance:${curr},change amount:${amount}`;
|
||||||
|
}
|
||||||
|
}
|
21
src/commons/exceptions/application.exception.ts
Normal file
21
src/commons/exceptions/application.exception.ts
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
export class ApplicationException extends Error {
|
||||||
|
code: number;
|
||||||
|
error: Error;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
message:
|
||||||
|
| string
|
||||||
|
| { error?: Error; message?: string | object; code?: number },
|
||||||
|
) {
|
||||||
|
if (message instanceof Object) {
|
||||||
|
super();
|
||||||
|
this.code = message.code;
|
||||||
|
this.error = message.error;
|
||||||
|
this.message = message.message as any;
|
||||||
|
} else if (typeof message === 'string') {
|
||||||
|
super((message as unknown) as any);
|
||||||
|
} else {
|
||||||
|
super((message as unknown) as any);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
35
src/commons/exceptions/duplicate-entity.exception.ts
Normal file
35
src/commons/exceptions/duplicate-entity.exception.ts
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import { ValidationError } from '@nestjs/common';
|
||||||
|
import { WrongContentException } from './wrong-content.exception';
|
||||||
|
|
||||||
|
export interface DuplicateFieldInfo {
|
||||||
|
property: string;
|
||||||
|
value: any;
|
||||||
|
name?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DuplicateEntityException extends WrongContentException {
|
||||||
|
errorObj: { [p: string]: any; message: ValidationError[] };
|
||||||
|
constructor(exceptionInfo: DuplicateFieldInfo[]) {
|
||||||
|
super(DuplicateEntityException.getValidationError(exceptionInfo));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static getValidationError(
|
||||||
|
exceptionInfo: DuplicateFieldInfo[],
|
||||||
|
): ValidationError[] {
|
||||||
|
return exceptionInfo.map((item) => {
|
||||||
|
const property: string = item.property;
|
||||||
|
const value: any = item.value;
|
||||||
|
const message: string = item.message
|
||||||
|
? item.message
|
||||||
|
: `${item.name || ''}已存在相同的值「${item.value}」`;
|
||||||
|
return {
|
||||||
|
property,
|
||||||
|
value,
|
||||||
|
constraints: { duplicate: message },
|
||||||
|
target: undefined,
|
||||||
|
children: [],
|
||||||
|
} as ValidationError;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
6
src/commons/exceptions/lock-failed.exception.ts
Normal file
6
src/commons/exceptions/lock-failed.exception.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export class LockFailedException extends Error {
|
||||||
|
constructor(lockId: any) {
|
||||||
|
super();
|
||||||
|
this.message = `加锁失败。目标:${lockId}`;
|
||||||
|
}
|
||||||
|
}
|
36
src/commons/exceptions/value-out-of-range.exception.ts
Normal file
36
src/commons/exceptions/value-out-of-range.exception.ts
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import { ValidationError } from '@nestjs/common';
|
||||||
|
import { WrongContentException } from './wrong-content.exception';
|
||||||
|
|
||||||
|
export interface ValueOutOfRangeInfo {
|
||||||
|
property: string;
|
||||||
|
value: any;
|
||||||
|
range: string;
|
||||||
|
name?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ValueOutOfRangeException extends WrongContentException {
|
||||||
|
errorObj: { [p: string]: any; message: ValidationError[] };
|
||||||
|
constructor(exceptionInfo: ValueOutOfRangeInfo[]) {
|
||||||
|
super(ValueOutOfRangeException.getValidationError(exceptionInfo));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static getValidationError(
|
||||||
|
exceptionInfo: ValueOutOfRangeInfo[],
|
||||||
|
): ValidationError[] {
|
||||||
|
return exceptionInfo.map((item) => {
|
||||||
|
const property: string = item.property;
|
||||||
|
const value: any = item.value;
|
||||||
|
const message: string = item.message
|
||||||
|
? item.message
|
||||||
|
: `${item.name || ''}的取值范围应是${item.range}`;
|
||||||
|
return {
|
||||||
|
property,
|
||||||
|
value,
|
||||||
|
constraints: { duplicate: message },
|
||||||
|
target: undefined,
|
||||||
|
children: [],
|
||||||
|
} as ValidationError;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
7
src/commons/exceptions/wrong-content.exception.ts
Normal file
7
src/commons/exceptions/wrong-content.exception.ts
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import { UnprocessableEntityException, ValidationError } from '@nestjs/common';
|
||||||
|
|
||||||
|
export class WrongContentException extends UnprocessableEntityException {
|
||||||
|
constructor(exceptionInfo: ValidationError[]) {
|
||||||
|
super(exceptionInfo);
|
||||||
|
}
|
||||||
|
}
|
51
src/commons/filters/all.exception-filter.ts
Normal file
51
src/commons/filters/all.exception-filter.ts
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
import {
|
||||||
|
ExceptionFilter,
|
||||||
|
Catch,
|
||||||
|
ArgumentsHost,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApolloError } from 'apollo-server-errors';
|
||||||
|
|
||||||
|
@Catch(HttpException)
|
||||||
|
export class HttpExceptionFilter implements ExceptionFilter {
|
||||||
|
catch(exception: HttpException, host: ArgumentsHost) {
|
||||||
|
switch (host.getType<'http' | 'graphql' | string>()) {
|
||||||
|
case 'graphql': {
|
||||||
|
const message = exception.message;
|
||||||
|
const extensions: Record<string, any> = {};
|
||||||
|
const err = exception.getResponse();
|
||||||
|
if (typeof err === 'string') {
|
||||||
|
extensions.message = err;
|
||||||
|
} else {
|
||||||
|
Object.assign(extensions, (err as any).extension);
|
||||||
|
extensions.message = (err as any).message;
|
||||||
|
}
|
||||||
|
return new ApolloError(
|
||||||
|
message,
|
||||||
|
exception.getStatus().toString(),
|
||||||
|
extensions,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'http': {
|
||||||
|
const ctx = host.switchToHttp();
|
||||||
|
const response = ctx.getResponse();
|
||||||
|
const request = ctx.getRequest();
|
||||||
|
|
||||||
|
const status =
|
||||||
|
exception instanceof HttpException
|
||||||
|
? exception.getStatus()
|
||||||
|
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
|
||||||
|
response.status(status).json({
|
||||||
|
statusCode: status,
|
||||||
|
message: exception.message,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
path: request.url,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
3
src/commons/interfaces/available.interface.ts
Normal file
3
src/commons/interfaces/available.interface.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export interface AvailableInterface {
|
||||||
|
isAvailable: boolean;
|
||||||
|
}
|
6
src/commons/interfaces/pagination.interface.ts
Normal file
6
src/commons/interfaces/pagination.interface.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export interface PaginationInterface {
|
||||||
|
pageSize?: number;
|
||||||
|
pageIndex?: number;
|
||||||
|
take?: number;
|
||||||
|
skip?: number;
|
||||||
|
}
|
7
src/commons/middleware/parse-body.middleware.spec.ts
Normal file
7
src/commons/middleware/parse-body.middleware.spec.ts
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import { ParseBodyMiddleware } from './parse-body.middleware';
|
||||||
|
|
||||||
|
describe('ParseBodyMiddleware', () => {
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(new ParseBodyMiddleware()).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
13
src/commons/middleware/parse-body.middleware.ts
Normal file
13
src/commons/middleware/parse-body.middleware.ts
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
|
import { json, urlencoded, text } from 'body-parser';
|
||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ParseBodyMiddleware implements NestMiddleware {
|
||||||
|
use(req: Request, res: Response, next: NextFunction) {
|
||||||
|
json()(req, res, () =>
|
||||||
|
urlencoded()(req, res, () => text()(req, res, next)),
|
||||||
|
);
|
||||||
|
// next();
|
||||||
|
}
|
||||||
|
}
|
7
src/commons/middleware/raw-body.middleware.spec.ts
Normal file
7
src/commons/middleware/raw-body.middleware.spec.ts
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import { RawBodyMiddleware } from './raw-body.middleware';
|
||||||
|
|
||||||
|
describe('RawBodyMiddleware', () => {
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(new RawBodyMiddleware()).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
10
src/commons/middleware/raw-body.middleware.ts
Normal file
10
src/commons/middleware/raw-body.middleware.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
|
import { raw } from 'body-parser';
|
||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RawBodyMiddleware implements NestMiddleware {
|
||||||
|
use(req: Request, res: Response, next: NextFunction) {
|
||||||
|
raw({ type: '*/*' })(req, res, next);
|
||||||
|
}
|
||||||
|
}
|
25
src/commons/pipes/sanitize.pipe.ts
Normal file
25
src/commons/pipes/sanitize.pipe.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
|
||||||
|
import { plainToClass } from 'class-transformer';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SanitizePipe implements PipeTransform {
|
||||||
|
transform(value: any, metadata: ArgumentMetadata) {
|
||||||
|
if (
|
||||||
|
!(value instanceof Object) ||
|
||||||
|
value instanceof Buffer ||
|
||||||
|
value instanceof Array
|
||||||
|
) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
const constructorFunction = metadata.metatype;
|
||||||
|
if (!constructorFunction || value instanceof constructorFunction) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return plainToClass(constructorFunction, value);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
import { Inject } from '@nestjs/common';
|
||||||
|
import { getPubSubToken } from '../utils/token';
|
||||||
|
|
||||||
|
export const InjectPubSub = (name?: string): ParameterDecorator =>
|
||||||
|
Inject(getPubSubToken(name));
|
@ -0,0 +1,8 @@
|
|||||||
|
import { ModuleMetadata } from '@nestjs/common';
|
||||||
|
import { PubSubOptions } from './pub-sub-options.interface';
|
||||||
|
|
||||||
|
export interface PubSubAsyncConfig extends Pick<ModuleMetadata, 'imports'> {
|
||||||
|
name?: string;
|
||||||
|
useFactory: (...args: any[]) => Promise<PubSubOptions> | PubSubOptions;
|
||||||
|
inject?: any[];
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
import { RedisOptions } from 'ioredis';
|
||||||
|
|
||||||
|
export interface PubSubOptions {
|
||||||
|
name?: string;
|
||||||
|
redis: RedisOptions;
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
export type PubSubRawMessage<T> =
|
||||||
|
| PubSubRawNextMessage<T>
|
||||||
|
| PubSubRawErrorMessage<T>
|
||||||
|
| PubSubRawCompleteMessage<T>;
|
||||||
|
export interface PubSubRawNextMessage<T> {
|
||||||
|
type: 'next';
|
||||||
|
message: T;
|
||||||
|
}
|
||||||
|
export interface PubSubRawErrorMessage<T> {
|
||||||
|
type: 'error';
|
||||||
|
error: string;
|
||||||
|
}
|
||||||
|
export interface PubSubRawCompleteMessage<T> {
|
||||||
|
type: 'complete';
|
||||||
|
}
|
1
src/commons/pub-sub/pub-sub.constants.ts
Normal file
1
src/commons/pub-sub/pub-sub.constants.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export const DEFAULT_PUB_SUB_NAME = 'default';
|
48
src/commons/pub-sub/pub-sub.module.ts
Normal file
48
src/commons/pub-sub/pub-sub.module.ts
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
import { DynamicModule, Module } from '@nestjs/common';
|
||||||
|
import { PubSubService } from './pub-sub.service';
|
||||||
|
import {
|
||||||
|
createAsyncPubSubProviders,
|
||||||
|
createPubSubProvider,
|
||||||
|
} from './pub-sub.providers';
|
||||||
|
import { PubSubOptions } from './interfaces/pub-sub-options.interface';
|
||||||
|
import { PubSubAsyncConfig } from './interfaces/pub-sub-async-config.interface';
|
||||||
|
import { getPubSubConfigToken } from './utils/token';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [PubSubService],
|
||||||
|
})
|
||||||
|
export class PubSubModule {
|
||||||
|
public static forRoot(options: PubSubOptions): DynamicModule {
|
||||||
|
const providers = [
|
||||||
|
{
|
||||||
|
provide: getPubSubConfigToken(options.name),
|
||||||
|
useValue: options,
|
||||||
|
},
|
||||||
|
createPubSubProvider(options.name),
|
||||||
|
];
|
||||||
|
return {
|
||||||
|
global: true,
|
||||||
|
module: PubSubModule,
|
||||||
|
providers,
|
||||||
|
exports: providers,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public static forRootAsync(...configs: PubSubAsyncConfig[]): DynamicModule {
|
||||||
|
const providers = createAsyncPubSubProviders(configs);
|
||||||
|
return {
|
||||||
|
global: true,
|
||||||
|
module: PubSubModule,
|
||||||
|
imports: configs
|
||||||
|
.map((config) => config.imports)
|
||||||
|
.flat()
|
||||||
|
.filter((o, i, a) => a.indexOf(o) === i),
|
||||||
|
providers,
|
||||||
|
exports: providers,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public static forFeature(): DynamicModule {
|
||||||
|
return {
|
||||||
|
module: PubSubModule,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
31
src/commons/pub-sub/pub-sub.providers.ts
Normal file
31
src/commons/pub-sub/pub-sub.providers.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import { Provider } from '@nestjs/common';
|
||||||
|
import { PubSubAsyncConfig } from './interfaces/pub-sub-async-config.interface';
|
||||||
|
import { PubSubOptions } from './interfaces/pub-sub-options.interface';
|
||||||
|
import { PubSub } from './pub-sub';
|
||||||
|
import { getPubSubConfigToken, getPubSubToken } from './utils/token';
|
||||||
|
|
||||||
|
export function createPubSubProvider(name: string): Provider {
|
||||||
|
return {
|
||||||
|
provide: getPubSubToken(name),
|
||||||
|
useFactory: (option: PubSubOptions) => new PubSub(option),
|
||||||
|
inject: [getPubSubConfigToken(name)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createOptionsProvider(config: PubSubAsyncConfig): Provider {
|
||||||
|
return {
|
||||||
|
provide: getPubSubConfigToken(config.name),
|
||||||
|
useFactory: config.useFactory,
|
||||||
|
inject: config.inject || [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function createAsyncPubSubProviders(
|
||||||
|
configs: PubSubAsyncConfig[],
|
||||||
|
): Provider[] {
|
||||||
|
return configs
|
||||||
|
.map((config) => [
|
||||||
|
createOptionsProvider(config),
|
||||||
|
createPubSubProvider(config.name),
|
||||||
|
])
|
||||||
|
.flat();
|
||||||
|
}
|
18
src/commons/pub-sub/pub-sub.service.spec.ts
Normal file
18
src/commons/pub-sub/pub-sub.service.spec.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PubSubService } from './pub-sub.service';
|
||||||
|
|
||||||
|
describe('PubsubService', () => {
|
||||||
|
let service: PubSubService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [PubSubService],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<PubSubService>(PubSubService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
9
src/commons/pub-sub/pub-sub.service.ts
Normal file
9
src/commons/pub-sub/pub-sub.service.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PubSubOptions } from './interfaces/pub-sub-options.interface';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PubSubService {
|
||||||
|
private options = new Map<string, PubSubOptions>();
|
||||||
|
private pubClient;
|
||||||
|
private;
|
||||||
|
}
|
87
src/commons/pub-sub/pub-sub.spec.ts
Normal file
87
src/commons/pub-sub/pub-sub.spec.ts
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
import debug from 'debug';
|
||||||
|
import { tap } from 'rxjs/operators';
|
||||||
|
import { PubSub } from './pub-sub';
|
||||||
|
|
||||||
|
debug.enable('app:pubsub:*');
|
||||||
|
|
||||||
|
describe('PubSub', () => {
|
||||||
|
let instance: PubSub;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
instance = new PubSub({
|
||||||
|
name: 'default',
|
||||||
|
redis: {
|
||||||
|
host: 'localhost',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(instance).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should can send and receive message', async () => {
|
||||||
|
const arr = new Array(10)
|
||||||
|
.fill(undefined)
|
||||||
|
.map(() => Math.random().toString(36).slice(2, 8));
|
||||||
|
const results: string[] = [];
|
||||||
|
instance
|
||||||
|
.message$<string>('test')
|
||||||
|
.pipe(
|
||||||
|
tap((val) => {
|
||||||
|
console.log(val);
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.subscribe((val) => results.push(val));
|
||||||
|
await new Promise((r) => setTimeout(r, 1000));
|
||||||
|
await Promise.all([...arr.map((str) => instance.publish('test', str))]);
|
||||||
|
await new Promise((r) => setTimeout(r, 1000));
|
||||||
|
expect(results).toMatchObject(arr);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should complete', async () => {
|
||||||
|
const arr = new Array(10)
|
||||||
|
.fill(undefined)
|
||||||
|
.map(() => Math.random().toString(36).slice(2, 8));
|
||||||
|
const results: string[] = [];
|
||||||
|
instance
|
||||||
|
.message$<string>('test')
|
||||||
|
.pipe(
|
||||||
|
tap((val) => {
|
||||||
|
console.log(val);
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.subscribe((val) => results.push(val));
|
||||||
|
await new Promise((r) => setTimeout(r, 1000));
|
||||||
|
await Promise.all([...arr.map((str) => instance.publish('test', str))]);
|
||||||
|
await instance.finish('test');
|
||||||
|
await Promise.all([...arr.map((str) => instance.publish('test', str))]);
|
||||||
|
await new Promise((r) => setTimeout(r, 1000));
|
||||||
|
expect(results).toMatchObject(arr);
|
||||||
|
});
|
||||||
|
it('should error', async () => {
|
||||||
|
const arr = new Array(10)
|
||||||
|
.fill(undefined)
|
||||||
|
.map(() => Math.random().toString(36).slice(2, 8));
|
||||||
|
const results: string[] = [];
|
||||||
|
let error: string;
|
||||||
|
instance
|
||||||
|
.message$<string>('test')
|
||||||
|
.pipe(
|
||||||
|
tap((val) => {
|
||||||
|
console.log(val);
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.subscribe({
|
||||||
|
next: (val) => results.push(val),
|
||||||
|
error: (err) => (error = err.message),
|
||||||
|
});
|
||||||
|
await new Promise((r) => setTimeout(r, 1000));
|
||||||
|
await Promise.all([...arr.map((str) => instance.publish('test', str))]);
|
||||||
|
await instance.throwError('test', 'TEST ERROR MESSAGE');
|
||||||
|
await Promise.all([...arr.map((str) => instance.publish('test', str))]);
|
||||||
|
await new Promise((r) => setTimeout(r, 1000));
|
||||||
|
expect(results).toMatchObject(arr);
|
||||||
|
expect(error).toEqual('TEST ERROR MESSAGE');
|
||||||
|
});
|
||||||
|
});
|
115
src/commons/pub-sub/pub-sub.ts
Normal file
115
src/commons/pub-sub/pub-sub.ts
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
import debug from 'debug';
|
||||||
|
import { EventEmitter } from 'events';
|
||||||
|
import IORedis, { Redis } from 'ioredis';
|
||||||
|
import { from, fromEvent, Observable } from 'rxjs';
|
||||||
|
import { filter, map, share, switchMap, takeWhile, tap } from 'rxjs/operators';
|
||||||
|
import { ApplicationException } from '../exceptions/application.exception';
|
||||||
|
import { PubSubOptions } from './interfaces/pub-sub-options.interface';
|
||||||
|
import {
|
||||||
|
PubSubRawMessage,
|
||||||
|
PubSubRawNextMessage,
|
||||||
|
} from './interfaces/pub-sub-raw-message.interface';
|
||||||
|
|
||||||
|
const log = debug('fennec:pubsub:instance');
|
||||||
|
export class PubSub extends EventEmitter {
|
||||||
|
pubRedis: Redis;
|
||||||
|
pSubRedis: Redis;
|
||||||
|
channels: string[] = [];
|
||||||
|
event$: Observable<[string, string, any]>;
|
||||||
|
|
||||||
|
constructor(private readonly options: PubSubOptions) {
|
||||||
|
super();
|
||||||
|
this.pubRedis = new IORedis(this.options.redis);
|
||||||
|
this.pSubRedis = new IORedis(this.options.redis);
|
||||||
|
|
||||||
|
this.pSubRedis.on('pmessage', (...args) =>
|
||||||
|
log.extend('raw')('%s %s %o', ...args),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.event$ = fromEvent<[string, string, string]>(
|
||||||
|
this.pSubRedis,
|
||||||
|
'pmessage',
|
||||||
|
).pipe(
|
||||||
|
map((ev) => {
|
||||||
|
try {
|
||||||
|
ev[2] = JSON.parse(ev[2]);
|
||||||
|
} catch (err) {
|
||||||
|
log('WARN: is not json');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
log('on message: %s %s %o', ...ev);
|
||||||
|
return ev;
|
||||||
|
}),
|
||||||
|
filter((v) => !!v),
|
||||||
|
share(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async disconnect() {
|
||||||
|
log('disconnecting to redis...');
|
||||||
|
this.pubRedis.disconnect();
|
||||||
|
this.pSubRedis.disconnect();
|
||||||
|
log('disconnected');
|
||||||
|
}
|
||||||
|
|
||||||
|
async registerChannel(channel: string) {
|
||||||
|
if (this.channels.includes(channel)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.channels.push(channel);
|
||||||
|
|
||||||
|
return await this.pSubRedis.psubscribe(channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async redisPublish<T>(channel: string, message: PubSubRawMessage<T>) {
|
||||||
|
log.extend('publish')('channel: %s, message: %O', channel, message);
|
||||||
|
return await this.pubRedis.publish(channel, JSON.stringify(message));
|
||||||
|
}
|
||||||
|
|
||||||
|
async publish(channel: string, message: any): Promise<number> {
|
||||||
|
return await this.redisPublish(channel, {
|
||||||
|
type: 'next',
|
||||||
|
message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async finish(channel: string): Promise<number> {
|
||||||
|
return await this.redisPublish(channel, {
|
||||||
|
type: 'complete',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async throwError(channel: string, error: string): Promise<number> {
|
||||||
|
return await this.redisPublish(channel, {
|
||||||
|
type: 'error',
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
message$ = <T>(channel: string): Observable<T> => {
|
||||||
|
return from(this.registerChannel(channel))
|
||||||
|
.pipe(switchMap(() => this.event$))
|
||||||
|
.pipe(
|
||||||
|
filter(([pattern]) => pattern === channel),
|
||||||
|
tap(([pattern, channel, message]) => {
|
||||||
|
log.extend('subscribe')(
|
||||||
|
'channel: %s, match: %s, message: %O',
|
||||||
|
channel,
|
||||||
|
pattern,
|
||||||
|
message,
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
takeWhile(([pattern, channel, message]) => {
|
||||||
|
if (pattern === channel) {
|
||||||
|
if (message.type === 'error') {
|
||||||
|
throw new ApplicationException(message.error);
|
||||||
|
}
|
||||||
|
return message.type !== 'complete';
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
map((ev) => ev[2] as PubSubRawMessage<T>),
|
||||||
|
map((message: PubSubRawNextMessage<T>) => message.message),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
8
src/commons/pub-sub/utils/token.ts
Normal file
8
src/commons/pub-sub/utils/token.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import { DEFAULT_PUB_SUB_NAME } from '../pub-sub.constants';
|
||||||
|
|
||||||
|
export function getPubSubToken(name = DEFAULT_PUB_SUB_NAME) {
|
||||||
|
return `app:pub-usb:${name || DEFAULT_PUB_SUB_NAME}`;
|
||||||
|
}
|
||||||
|
export function getPubSubConfigToken(name = DEFAULT_PUB_SUB_NAME) {
|
||||||
|
return `app:pub-usb:config:${name || DEFAULT_PUB_SUB_NAME}`;
|
||||||
|
}
|
179
src/commons/services/base-db.service.ts
Normal file
179
src/commons/services/base-db.service.ts
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
import { AppBaseEntity } from '../entities/app-base-entity';
|
||||||
|
import { Brackets, Repository, SelectQueryBuilder } from 'typeorm';
|
||||||
|
import { TypeormHelper } from './typeorm-helper';
|
||||||
|
import { UnprocessableEntityException } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
DuplicateEntityException,
|
||||||
|
DuplicateFieldInfo,
|
||||||
|
} from '../exceptions/duplicate-entity.exception';
|
||||||
|
|
||||||
|
export class BaseDbService<Entity extends AppBaseEntity> extends TypeormHelper {
|
||||||
|
constructor(protected readonly repository: Repository<Entity>) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
readonly uniqueFields: Array<keyof Entity | Array<keyof Entity>> = [];
|
||||||
|
|
||||||
|
async isDuplicateEntity<Dto extends Entity & Record<string, any>>(
|
||||||
|
dto: Partial<Dto>,
|
||||||
|
extendsFields: Array<keyof Dto> = [],
|
||||||
|
): Promise<false | never> {
|
||||||
|
const qb = this.repository.createQueryBuilder('entity');
|
||||||
|
const compareFields = this.getCompareFields(dto, [
|
||||||
|
...this.uniqueFields,
|
||||||
|
...extendsFields,
|
||||||
|
]);
|
||||||
|
if (compareFields.length > 0) {
|
||||||
|
qb.andWhere(
|
||||||
|
new Brackets((bqb) => {
|
||||||
|
for (const key of compareFields) {
|
||||||
|
if (Array.isArray(key)) {
|
||||||
|
bqb.orWhere(
|
||||||
|
new Brackets((bbqb) => {
|
||||||
|
for (const k of key) {
|
||||||
|
bbqb.andWhere(`entity.${k} = :${k}`);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
bqb.orWhere(`entity.${key} = :${key}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
qb.setParameters(Object.assign({}, dto));
|
||||||
|
const uniqueFields = Array.from(new Set(compareFields.flat()));
|
||||||
|
qb.addSelect(uniqueFields.map((f) => `entity.${f} AS entity_${f}`));
|
||||||
|
return await this.checkDuplicateFields(qb, dto, uniqueFields);
|
||||||
|
}
|
||||||
|
|
||||||
|
async isDuplicateEntityForUpdate<Dto extends Entity>(
|
||||||
|
id: string,
|
||||||
|
dto: Partial<Dto>,
|
||||||
|
extendsFields: Array<keyof Dto & string> = [],
|
||||||
|
): Promise<false | never> {
|
||||||
|
const qb = this.repository.createQueryBuilder('entity');
|
||||||
|
const compareFields = this.getCompareFields(dto, [
|
||||||
|
...this.uniqueFields,
|
||||||
|
...extendsFields,
|
||||||
|
]);
|
||||||
|
const flatCompareFields = compareFields.flat();
|
||||||
|
if (compareFields.length > 0) {
|
||||||
|
qb.andWhere(
|
||||||
|
new Brackets((bqb) => {
|
||||||
|
for (const key of compareFields) {
|
||||||
|
if (Array.isArray(key)) {
|
||||||
|
if (key.length > 0) {
|
||||||
|
bqb.orWhere(
|
||||||
|
new Brackets((bbqb) =>
|
||||||
|
key.forEach((k) => {
|
||||||
|
bbqb.andWhere(`entity.${k} = :${k}`);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
bqb.orWhere(`entity.${key} = :${key}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
qb.andWhere(`entity.id <> :id`);
|
||||||
|
qb.setParameters(Object.assign({}, dto, { id }));
|
||||||
|
qb.addSelect(flatCompareFields.map((f) => `entity.${f} AS entity_${f}`));
|
||||||
|
return await this.checkDuplicateFields(qb, dto, compareFields);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(entity: Entity): Promise<Entity>;
|
||||||
|
async findOne(id: string): Promise<Entity>;
|
||||||
|
async findOne(idOrEntity: string | Entity): Promise<Entity> {
|
||||||
|
if (idOrEntity instanceof Object) {
|
||||||
|
return idOrEntity;
|
||||||
|
}
|
||||||
|
return await this.repository.findOneOrFail({
|
||||||
|
where: { id: idOrEntity },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
checkProperty<T>(
|
||||||
|
obj: T,
|
||||||
|
field: keyof T,
|
||||||
|
whitelist: Array<typeof obj[keyof T]>,
|
||||||
|
errMsg: string,
|
||||||
|
) {
|
||||||
|
if (!whitelist.some((item) => obj[field] === item)) {
|
||||||
|
throw new UnprocessableEntityException(errMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async canYouRemoveWithIds(ids: string[]): Promise<void> {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getCompareFields<Dto>(
|
||||||
|
dto: Partial<Dto>,
|
||||||
|
fields: Array<keyof Dto | Array<keyof Dto>>,
|
||||||
|
) {
|
||||||
|
if (!Array.isArray(fields)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const compareFields = [];
|
||||||
|
for (const field of fields as Array<keyof Dto | Array<keyof Dto>>) {
|
||||||
|
if (Array.isArray(field)) {
|
||||||
|
const tmpFields = [];
|
||||||
|
for (const f of field) {
|
||||||
|
if (dto[f] !== undefined) {
|
||||||
|
tmpFields.push(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compareFields.push(tmpFields);
|
||||||
|
} else if (dto[field] !== undefined) {
|
||||||
|
compareFields.push(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return compareFields;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkDuplicateFields<Dto = { [p: string]: any }>(
|
||||||
|
qb: SelectQueryBuilder<Entity>,
|
||||||
|
dto: Dto,
|
||||||
|
compareFields: Array<keyof Dto & string>,
|
||||||
|
): Promise<false | never> {
|
||||||
|
const existingEntity = await qb.getOne();
|
||||||
|
if (!existingEntity) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const duplicateEntityInfo: DuplicateFieldInfo[] = [];
|
||||||
|
for (const key of compareFields) {
|
||||||
|
if (existingEntity[key as string] === dto[key]) {
|
||||||
|
duplicateEntityInfo.push({
|
||||||
|
property: key,
|
||||||
|
value: dto[key],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new DuplicateEntityException(duplicateEntityInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async getTotalQueryBuilder(
|
||||||
|
qb: SelectQueryBuilder<Entity>,
|
||||||
|
): Promise<SelectQueryBuilder<Entity>> {
|
||||||
|
const totalQb = qb.clone();
|
||||||
|
totalQb.offset(0).skip(0).take(undefined).limit(undefined);
|
||||||
|
return totalQb;
|
||||||
|
}
|
||||||
|
|
||||||
|
getUpdateRows(returned: any): number {
|
||||||
|
return returned?.affected;
|
||||||
|
}
|
||||||
|
|
||||||
|
isFindOne(queryArg): boolean {
|
||||||
|
return queryArg.id !== undefined;
|
||||||
|
}
|
||||||
|
}
|
15
src/commons/services/password-converter.ts
Normal file
15
src/commons/services/password-converter.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { compare, genSalt, hash } from 'bcrypt';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PasswordConverter {
|
||||||
|
async convertToStore(pwd: string | undefined): Promise<string> {
|
||||||
|
if (pwd === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return await hash(pwd, await genSalt());
|
||||||
|
}
|
||||||
|
async compare(rawPwd: string, storePwd: string): Promise<boolean> {
|
||||||
|
return await compare(rawPwd, storePwd);
|
||||||
|
}
|
||||||
|
}
|
304
src/commons/services/typeorm-helper.ts
Normal file
304
src/commons/services/typeorm-helper.ts
Normal file
@ -0,0 +1,304 @@
|
|||||||
|
import { SelectQueryBuilder } from 'typeorm';
|
||||||
|
|
||||||
|
interface PaginationInterface {
|
||||||
|
pageSize?: number;
|
||||||
|
pageIndex?: number;
|
||||||
|
take?: number;
|
||||||
|
skip?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TypeormHelper {
|
||||||
|
static pagination<T>(qb: SelectQueryBuilder<T>, params: PaginationInterface) {
|
||||||
|
if (!params.take || isNaN(params.take)) {
|
||||||
|
if (!params.pageSize || isNaN(params.pageSize)) {
|
||||||
|
params.pageSize = 50;
|
||||||
|
}
|
||||||
|
params.take = params.pageSize;
|
||||||
|
}
|
||||||
|
if (!params.skip || isNaN(params.skip)) {
|
||||||
|
if (!params.pageIndex || isNaN(params.pageIndex)) {
|
||||||
|
params.pageIndex = 1;
|
||||||
|
}
|
||||||
|
params.skip = (params.pageIndex - 1) * params.pageSize;
|
||||||
|
}
|
||||||
|
if (params.skip) {
|
||||||
|
qb.skip(params.skip);
|
||||||
|
}
|
||||||
|
if (params.take) {
|
||||||
|
qb.take(params.take);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static pagination4Raw<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
params: PaginationInterface,
|
||||||
|
) {
|
||||||
|
if (!params.take || isNaN(params.take)) {
|
||||||
|
if (!params.pageSize || isNaN(params.pageSize)) {
|
||||||
|
params.pageSize = 15;
|
||||||
|
}
|
||||||
|
params.take = params.pageSize;
|
||||||
|
}
|
||||||
|
if (!params.skip || isNaN(params.skip)) {
|
||||||
|
if (!params.pageIndex || isNaN(params.pageIndex)) {
|
||||||
|
params.pageIndex = 1;
|
||||||
|
}
|
||||||
|
params.skip = (params.pageIndex - 1) * params.pageSize;
|
||||||
|
}
|
||||||
|
if (params.skip) {
|
||||||
|
qb.offset(params.skip);
|
||||||
|
}
|
||||||
|
if (params.take) {
|
||||||
|
qb.limit(params.take);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterActive<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
params: { isActive?: boolean },
|
||||||
|
) {
|
||||||
|
if (params.isActive === true || params.isActive === false) {
|
||||||
|
qb.andWhere(`${alias}.isActive = :isActive`, params);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterDeletion<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
params: { isDelete?: boolean; includeDeleted?: boolean },
|
||||||
|
) {
|
||||||
|
if (params.isDelete && params.includeDeleted) {
|
||||||
|
qb.andWhere(`${alias}.isDelete = true`);
|
||||||
|
} else if (params.isDelete === false || !params.includeDeleted) {
|
||||||
|
qb.andWhere(`${alias}.isDelete = false`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static rangeFilter<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
fieldName: string,
|
||||||
|
params,
|
||||||
|
) {
|
||||||
|
const beginAt = params[`${fieldName}GT`];
|
||||||
|
const endAt = params[`${fieldName}LT`];
|
||||||
|
if (beginAt) {
|
||||||
|
qb.andWhere(`${alias}.${fieldName} >= :${`${fieldName}GT`}`, {
|
||||||
|
[`${fieldName}GT`]: beginAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (endAt) {
|
||||||
|
qb.andWhere(`${alias}.${fieldName} <= :${`${fieldName}LT`}`, {
|
||||||
|
[`${fieldName}LT`]: endAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static dateTimeRangeFilter2<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
fieldName: string,
|
||||||
|
beginAt: Date,
|
||||||
|
endAt: Date,
|
||||||
|
) {
|
||||||
|
if (beginAt) {
|
||||||
|
qb.andWhere(`${alias}.${fieldName} >= :beginAt`, { beginAt });
|
||||||
|
}
|
||||||
|
if (endAt) {
|
||||||
|
qb.andWhere(`${alias}.${fieldName} <= :endAt`, { endAt });
|
||||||
|
qb.andWhere(`${alias}.${fieldName} >= :${fieldName}BeginAt`, {
|
||||||
|
[`${fieldName}BeginAt`]: beginAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (endAt) {
|
||||||
|
qb.andWhere(`${alias}.${fieldName} <= :${fieldName}EndAt`, {
|
||||||
|
[`${fieldName}EndAt`]: endAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static baseQuery<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
params: {
|
||||||
|
isDelete?: boolean;
|
||||||
|
includeDeleted?: boolean;
|
||||||
|
isActive?: boolean;
|
||||||
|
} & PaginationInterface,
|
||||||
|
) {
|
||||||
|
this.filterByIds(qb, alias, params);
|
||||||
|
this.pagination(qb, params);
|
||||||
|
this.filterActive(qb, alias, params);
|
||||||
|
this.filterDeletion(qb, alias, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
static excludeDeletedRecords<T>(qb: SelectQueryBuilder<T>, alias: string) {
|
||||||
|
qb.andWhere(`${alias}.isDelete = FALSE`);
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterBoolean<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
params: any,
|
||||||
|
) {
|
||||||
|
for (const key of Object.keys(params)) {
|
||||||
|
if (params[key] === true || params[key] === false) {
|
||||||
|
const sql = `${alias}.${key} = :${key}`;
|
||||||
|
qb.andWhere(sql, { [key]: params[key] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterBooleanWhenExists<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
field: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
params[field] !== undefined &&
|
||||||
|
params[field] !== null &&
|
||||||
|
qb.andWhere(`${alias}.${field} = :${field}`, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterEqual<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
field: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
params[field] !== undefined &&
|
||||||
|
qb.andWhere(`${alias}.${field} = :${field}`, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
static sortResults<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
field: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
params[`${field}OrderBy`] !== undefined &&
|
||||||
|
qb.addOrderBy(`${alias}.${field}`, params[`${field}OrderBy`]);
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterLike<T, Conditions>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
field: string & (keyof Conditions | keyof T),
|
||||||
|
params: { [f: string]: any },
|
||||||
|
) {
|
||||||
|
params[field] &&
|
||||||
|
qb.andWhere(`${alias}.${field} LIKE :like-$${field}`, {
|
||||||
|
[`like-${field}`]: `%${params[field]}%`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterLike2<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
dbField: string,
|
||||||
|
pField: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
params[pField] &&
|
||||||
|
qb.andWhere(`${dbField} LIKE :like-$${pField}`, {
|
||||||
|
[`like-${pField}`]: `%${params[pField]}%`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterLike3<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
field: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
params[field] &&
|
||||||
|
qb.andWhere(`${alias}.${field} LIKE :like-${field}`, {
|
||||||
|
[`like-${field}`]: `${params[field]}%`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterNameOrRemark<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
nameField = 'name',
|
||||||
|
remarkField = 'remark',
|
||||||
|
pField = 'name',
|
||||||
|
) {
|
||||||
|
params[pField] &&
|
||||||
|
qb.andWhere((qb1) =>
|
||||||
|
qb1
|
||||||
|
.orWhere(`${nameField} LIKE :${pField}`, {
|
||||||
|
[pField]: `%${params[pField]}%`,
|
||||||
|
})
|
||||||
|
.orWhere(`${remarkField} LIKE :${pField}`, {
|
||||||
|
[pField]: `%${params[pField]}%`,
|
||||||
|
})
|
||||||
|
.getQuery(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterUserByIdOrName<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
entityName: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
TypeormHelper.filterEqual(qb, alias, `${entityName}Id`, params);
|
||||||
|
TypeormHelper.filterLike2(
|
||||||
|
qb,
|
||||||
|
`${entityName}.nick`,
|
||||||
|
`${entityName}Name`,
|
||||||
|
params,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterUserByIdOrName2<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
entityName: string,
|
||||||
|
field = 'name',
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
TypeormHelper.filterEqual(qb, alias, `${entityName}Id`, params);
|
||||||
|
TypeormHelper.filterLike2(
|
||||||
|
qb,
|
||||||
|
`${entityName}.${field}`,
|
||||||
|
`${entityName}Name`,
|
||||||
|
params,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterByIds<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
let ids = Array.isArray(params.ids) ? params.ids : [params.id];
|
||||||
|
ids = ids.filter((id) => !!id);
|
||||||
|
if (ids.length > 0) {
|
||||||
|
qb.andWhereInIds(ids);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static filterIn<T>(
|
||||||
|
qb: SelectQueryBuilder<T>,
|
||||||
|
alias: string,
|
||||||
|
dbField: string,
|
||||||
|
pField: string,
|
||||||
|
params: { [field: string]: any },
|
||||||
|
) {
|
||||||
|
if (!Array.isArray(params[pField])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (params[pField].length > 0) {
|
||||||
|
qb.andWhere(`${alias}.${dbField} IN (:...${pField})`, params);
|
||||||
|
} else {
|
||||||
|
qb.where('1 <> 1');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static getUserParentIds(user) {
|
||||||
|
return user.path.split('/').filter((v) => !!v);
|
||||||
|
}
|
||||||
|
}
|
7
src/hello.ts
Normal file
7
src/hello.ts
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import { Field, ObjectType } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class Hello {
|
||||||
|
@Field()
|
||||||
|
message: string;
|
||||||
|
}
|
20
src/main.ts
Normal file
20
src/main.ts
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import { HttpExceptionFilter } from './commons/filters/all.exception-filter';
|
||||||
|
import { SanitizePipe } from './commons/pipes/sanitize.pipe';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create(AppModule, { bodyParser: false });
|
||||||
|
const configService = app.get(ConfigService);
|
||||||
|
app.useGlobalPipes(new SanitizePipe());
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
transform: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
app.useGlobalFilters(new HttpExceptionFilter());
|
||||||
|
await app.listen(configService.get<number>('http.port'));
|
||||||
|
}
|
||||||
|
bootstrap();
|
24
test/app.e2e-spec.ts
Normal file
24
test/app.e2e-spec.ts
Normal file
@ -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!');
|
||||||
|
});
|
||||||
|
});
|
8
test/data/bad-work.js
Normal file
8
test/data/bad-work.js
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
for (let i = 1; i <= 5; i++) {
|
||||||
|
console.log(i * 10);
|
||||||
|
}
|
||||||
|
console.error('Error Message');
|
||||||
|
console.error('Error Message 2');
|
||||||
|
console.log('Bye-bye');
|
||||||
|
|
||||||
|
process.exit(1);
|
115
test/data/gitea-hook-payload.json.bin
Normal file
115
test/data/gitea-hook-payload.json.bin
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
{
|
||||||
|
"secret": "boardcat",
|
||||||
|
"ref": "refs/heads/master",
|
||||||
|
"before": "429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"after": "429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"compare_url": "",
|
||||||
|
"commits": [
|
||||||
|
{
|
||||||
|
"id": "429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"message": "test(pipeline-tasks): pass test cases.\n",
|
||||||
|
"url": "https://git.ivanli.cc/Fennec/fennec-be/commit/429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"author": {
|
||||||
|
"name": "Ivan",
|
||||||
|
"email": "ivanli@live.cn",
|
||||||
|
"username": ""
|
||||||
|
},
|
||||||
|
"committer": {
|
||||||
|
"name": "Ivan",
|
||||||
|
"email": "ivanli@live.cn",
|
||||||
|
"username": ""
|
||||||
|
},
|
||||||
|
"verification": null,
|
||||||
|
"timestamp": "0001-01-01T00:00:00Z",
|
||||||
|
"added": null,
|
||||||
|
"removed": null,
|
||||||
|
"modified": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"head_commit": null,
|
||||||
|
"repository": {
|
||||||
|
"id": 3,
|
||||||
|
"owner": {
|
||||||
|
"id": 3,
|
||||||
|
"login": "Fennec",
|
||||||
|
"full_name": "",
|
||||||
|
"email": "",
|
||||||
|
"avatar_url": "https://git.ivanli.cc/user/avatar/Fennec/-1",
|
||||||
|
"language": "",
|
||||||
|
"is_admin": false,
|
||||||
|
"last_login": "1970-01-01T08:00:00+08:00",
|
||||||
|
"created": "2021-01-30T16:46:11+08:00",
|
||||||
|
"username": "Fennec"
|
||||||
|
},
|
||||||
|
"name": "fennec-be",
|
||||||
|
"full_name": "Fennec/fennec-be",
|
||||||
|
"description": "Fennec CI/CD Back-End",
|
||||||
|
"empty": false,
|
||||||
|
"private": false,
|
||||||
|
"fork": false,
|
||||||
|
"template": false,
|
||||||
|
"parent": null,
|
||||||
|
"mirror": false,
|
||||||
|
"size": 1897,
|
||||||
|
"html_url": "https://git.ivanli.cc/Fennec/fennec-be",
|
||||||
|
"ssh_url": "ssh://gitea@git.ivanli.cc:7018/Fennec/fennec-be.git",
|
||||||
|
"clone_url": "https://git.ivanli.cc/Fennec/fennec-be.git",
|
||||||
|
"original_url": "",
|
||||||
|
"website": "",
|
||||||
|
"stars_count": 1,
|
||||||
|
"forks_count": 0,
|
||||||
|
"watchers_count": 1,
|
||||||
|
"open_issues_count": 0,
|
||||||
|
"open_pr_counter": 0,
|
||||||
|
"release_counter": 0,
|
||||||
|
"default_branch": "master",
|
||||||
|
"archived": false,
|
||||||
|
"created_at": "2021-01-31T09:58:38+08:00",
|
||||||
|
"updated_at": "2021-03-27T15:57:00+08:00",
|
||||||
|
"permissions": {
|
||||||
|
"admin": false,
|
||||||
|
"push": false,
|
||||||
|
"pull": false
|
||||||
|
},
|
||||||
|
"has_issues": true,
|
||||||
|
"internal_tracker": {
|
||||||
|
"enable_time_tracker": true,
|
||||||
|
"allow_only_contributors_to_track_time": true,
|
||||||
|
"enable_issue_dependencies": true
|
||||||
|
},
|
||||||
|
"has_wiki": true,
|
||||||
|
"has_pull_requests": true,
|
||||||
|
"has_projects": true,
|
||||||
|
"ignore_whitespace_conflicts": false,
|
||||||
|
"allow_merge_commits": true,
|
||||||
|
"allow_rebase": true,
|
||||||
|
"allow_rebase_explicit": true,
|
||||||
|
"allow_squash_merge": true,
|
||||||
|
"avatar_url": "",
|
||||||
|
"internal": false
|
||||||
|
},
|
||||||
|
"pusher": {
|
||||||
|
"id": 1,
|
||||||
|
"login": "Ivan",
|
||||||
|
"full_name": "Ivan Li",
|
||||||
|
"email": "ivan@noreply.%(DOMAIN)s",
|
||||||
|
"avatar_url": "https://git.ivanli.cc/user/avatar/Ivan/-1",
|
||||||
|
"language": "zh-CN",
|
||||||
|
"is_admin": true,
|
||||||
|
"last_login": "2021-03-26T22:28:05+08:00",
|
||||||
|
"created": "2021-01-23T18:15:30+08:00",
|
||||||
|
"username": "Ivan"
|
||||||
|
},
|
||||||
|
"sender": {
|
||||||
|
"id": 1,
|
||||||
|
"login": "Ivan",
|
||||||
|
"full_name": "Ivan Li",
|
||||||
|
"email": "ivan@noreply.%(DOMAIN)s",
|
||||||
|
"avatar_url": "https://git.ivanli.cc/user/avatar/Ivan/-1",
|
||||||
|
"language": "zh-CN",
|
||||||
|
"is_admin": true,
|
||||||
|
"last_login": "2021-03-26T22:28:05+08:00",
|
||||||
|
"created": "2021-01-23T18:15:30+08:00",
|
||||||
|
"username": "Ivan"
|
||||||
|
}
|
||||||
|
}
|
7
test/data/one-second-work.js
Normal file
7
test/data/one-second-work.js
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
let timer;
|
||||||
|
let count = 0;
|
||||||
|
setTimeout(() => clearInterval(timer), 1_000);
|
||||||
|
|
||||||
|
timer = setInterval(() => {
|
||||||
|
console.log(++count * 10);
|
||||||
|
}, 95);
|
9
test/jest-e2e.json
Normal file
9
test/jest-e2e.json
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": ".",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
}
|
||||||
|
}
|
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
15
tsconfig.json
Normal file
15
tsconfig.json
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "es2017",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user