feat: init project.

This commit is contained in:
Ivan Li
2021-04-17 13:54:26 +08:00
commit 7b715e807f
53 changed files with 14725 additions and 0 deletions

View 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
View 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
View 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
View 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
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View 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 {}

View 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;
};

View 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;
}

View File

@ -0,0 +1,6 @@
export class InsufficientBalanceException extends Error {
constructor(curr: number, amount: number) {
super();
this.message = `余额不足。current balance${curr}change amount${amount}`;
}
}

View 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);
}
}
}

View 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;
});
}
}

View File

@ -0,0 +1,6 @@
export class LockFailedException extends Error {
constructor(lockId: any) {
super();
this.message = `加锁失败。目标:${lockId}`;
}
}

View 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;
});
}
}

View File

@ -0,0 +1,7 @@
import { UnprocessableEntityException, ValidationError } from '@nestjs/common';
export class WrongContentException extends UnprocessableEntityException {
constructor(exceptionInfo: ValidationError[]) {
super(exceptionInfo);
}
}

View 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;
}
}
}

View File

@ -0,0 +1,3 @@
export interface AvailableInterface {
isAvailable: boolean;
}

View File

@ -0,0 +1,6 @@
export interface PaginationInterface {
pageSize?: number;
pageIndex?: number;
take?: number;
skip?: number;
}

View File

@ -0,0 +1,7 @@
import { ParseBodyMiddleware } from './parse-body.middleware';
describe('ParseBodyMiddleware', () => {
it('should be defined', () => {
expect(new ParseBodyMiddleware()).toBeDefined();
});
});

View 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();
}
}

View File

@ -0,0 +1,7 @@
import { RawBodyMiddleware } from './raw-body.middleware';
describe('RawBodyMiddleware', () => {
it('should be defined', () => {
expect(new RawBodyMiddleware()).toBeDefined();
});
});

View 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);
}
}

View 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;
}
}
}

View File

@ -0,0 +1,5 @@
import { Inject } from '@nestjs/common';
import { getPubSubToken } from '../utils/token';
export const InjectPubSub = (name?: string): ParameterDecorator =>
Inject(getPubSubToken(name));

View File

@ -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[];
}

View File

@ -0,0 +1,6 @@
import { RedisOptions } from 'ioredis';
export interface PubSubOptions {
name?: string;
redis: RedisOptions;
}

View File

@ -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';
}

View File

@ -0,0 +1 @@
export const DEFAULT_PUB_SUB_NAME = 'default';

View 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,
};
}
}

View 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();
}

View 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();
});
});

View 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;
}

View 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');
});
});

View 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),
);
};
}

View 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}`;
}

View 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;
}
}

View 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);
}
}

View 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
View File

@ -0,0 +1,7 @@
import { Field, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class Hello {
@Field()
message: string;
}

20
src/main.ts Normal file
View 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();