feat(proejct): project curd.
This commit is contained in:
@ -5,6 +5,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppResolver } from './app.resolver';
|
||||
import { AppService } from './app.service';
|
||||
import { ProjectsModule } from './projects/projects.module';
|
||||
import configuration from './commons/config/configuration';
|
||||
|
||||
@Module({
|
||||
@ -35,6 +36,7 @@ import configuration from './commons/config/configuration';
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
ProjectsModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService, AppResolver],
|
||||
|
8
src/commons/commons.module.ts
Normal file
8
src/commons/commons.module.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PasswordConverter } from './services/password-converter';
|
||||
|
||||
@Module({
|
||||
providers: [PasswordConverter],
|
||||
exports: [PasswordConverter],
|
||||
})
|
||||
export class CommonsModule {}
|
19
src/commons/entities/app-base-entity.ts
Normal file
19
src/commons/entities/app-base-entity.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||
import {
|
||||
CreateDateColumn,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@ObjectType()
|
||||
export class AppBaseEntity {
|
||||
@Field(() => ID)
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ select: false })
|
||||
updatedAt: 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);
|
||||
}
|
||||
}
|
55
src/commons/filters/all.exception-filter.ts
Normal file
55
src/commons/filters/all.exception-filter.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';
|
||||
|
||||
@Catch()
|
||||
export class AllExceptionsFilter implements ExceptionFilter {
|
||||
catch(exception: any, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse();
|
||||
const request = ctx.getRequest();
|
||||
|
||||
const status =
|
||||
exception instanceof HttpException
|
||||
? exception.getStatus()
|
||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
|
||||
if (exception instanceof HttpException) {
|
||||
const ex = exception.getResponse();
|
||||
if (ex instanceof Object) {
|
||||
response.status(status).json({
|
||||
...ex,
|
||||
timestamp: Date.now(),
|
||||
path: request.url,
|
||||
});
|
||||
} else {
|
||||
response.status(status).json({
|
||||
message: ex,
|
||||
timestamp: Date.now(),
|
||||
path: request.url,
|
||||
});
|
||||
}
|
||||
} else if (exception instanceof EntityNotFoundError) {
|
||||
response.status(HttpStatus.NOT_FOUND).json({
|
||||
message: '资源未找到!',
|
||||
timestamp: Date.now(),
|
||||
path: request.url,
|
||||
});
|
||||
} else {
|
||||
console.error('服务器内部错误');
|
||||
console.error(exception);
|
||||
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
|
||||
code: status,
|
||||
timestamp: new Date().toISOString(),
|
||||
message: '服务器内部错误',
|
||||
error: exception,
|
||||
path: request.url,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
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;
|
||||
}
|
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);
|
||||
}
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
@ -5,6 +6,7 @@ import { AppModule } from './app.module';
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const configService = app.get(ConfigService);
|
||||
app.useGlobalPipes(new ValidationPipe());
|
||||
await app.listen(configService.get<number>('http.port'));
|
||||
}
|
||||
bootstrap();
|
||||
|
28
src/projects/dtos/create-project.input.ts
Normal file
28
src/projects/dtos/create-project.input.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { InputType } from '@nestjs/graphql';
|
||||
import { IsString, IsUrl, MaxLength, MinLength } from 'class-validator';
|
||||
|
||||
@InputType({ isAbstract: true })
|
||||
export class CreateProjectInput {
|
||||
@IsString()
|
||||
@MaxLength(32)
|
||||
@MinLength(2)
|
||||
name: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(32)
|
||||
@MinLength(2)
|
||||
comment: string;
|
||||
|
||||
@IsUrl({ protocols: ['ssh'], require_protocol: false })
|
||||
@MaxLength(256)
|
||||
sshUrl: string;
|
||||
|
||||
@IsUrl()
|
||||
@MaxLength(256)
|
||||
webUrl?: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(128)
|
||||
@MinLength(1)
|
||||
webHookSecret?: string;
|
||||
}
|
5
src/projects/dtos/update-project.input.ts
Normal file
5
src/projects/dtos/update-project.input.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { InputType } from '@nestjs/graphql';
|
||||
import { CreateProjectInput } from './create-project.input';
|
||||
|
||||
@InputType()
|
||||
export class UpdateProjectInput extends CreateProjectInput {}
|
28
src/projects/project.entity.ts
Normal file
28
src/projects/project.entity.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { ObjectType } from '@nestjs/graphql';
|
||||
import { AppBaseEntity } from 'src/commons/entities/app-base-entity';
|
||||
import { Entity, Column, DeleteDateColumn } from 'typeorm';
|
||||
|
||||
@ObjectType()
|
||||
@Entity()
|
||||
export class Project extends AppBaseEntity {
|
||||
/**
|
||||
* 唯一名称
|
||||
*/
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@Column()
|
||||
comment: string;
|
||||
|
||||
@Column()
|
||||
sshUrl: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
webUrl?: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
webHookSecret?: string;
|
||||
|
||||
@DeleteDateColumn()
|
||||
deletedAt?: Date;
|
||||
}
|
11
src/projects/projects.module.ts
Normal file
11
src/projects/projects.module.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ProjectsService } from './projects.service';
|
||||
import { ProjectsResolver } from './projects.resolver';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Project } from './project.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Project])],
|
||||
providers: [ProjectsService, ProjectsResolver],
|
||||
})
|
||||
export class ProjectsModule {}
|
18
src/projects/projects.resolver.spec.ts
Normal file
18
src/projects/projects.resolver.spec.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ProjectsResolver } from './projects.resolver';
|
||||
|
||||
describe('ProjectsResolver', () => {
|
||||
let resolver: ProjectsResolver;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ProjectsResolver],
|
||||
}).compile();
|
||||
|
||||
resolver = module.get<ProjectsResolver>(ProjectsResolver);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(resolver).toBeDefined();
|
||||
});
|
||||
});
|
41
src/projects/projects.resolver.ts
Normal file
41
src/projects/projects.resolver.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
|
||||
import { CreateProjectInput } from './dtos/create-project.input';
|
||||
import { UpdateProjectInput } from './dtos/update-project.input';
|
||||
import { Project } from './project.entity';
|
||||
import { ProjectsService } from './projects.service';
|
||||
|
||||
@Resolver(() => Project)
|
||||
export class ProjectsResolver {
|
||||
constructor(private readonly service: ProjectsService) {}
|
||||
@Query(() => [Project])
|
||||
async findProjects() {
|
||||
return await this.service.list();
|
||||
}
|
||||
|
||||
@Query(() => Project)
|
||||
async findProject(@Args('id', { type: () => String }) id: string) {
|
||||
return await this.service.findOne(id);
|
||||
}
|
||||
|
||||
@Mutation(() => Project)
|
||||
async createProject(
|
||||
@Args('project', { type: () => CreateProjectInput })
|
||||
dto: UpdateProjectInput,
|
||||
) {
|
||||
return await this.service.create(dto);
|
||||
}
|
||||
|
||||
@Mutation(() => Boolean)
|
||||
async modifyProject(
|
||||
@Args('id', { type: () => String }) id: string,
|
||||
@Args('project', { type: () => UpdateProjectInput })
|
||||
dto: UpdateProjectInput,
|
||||
) {
|
||||
return await this.service.update(id, dto);
|
||||
}
|
||||
|
||||
@Mutation(() => Number)
|
||||
async deleteProject(@Args('id', { type: () => String }) id: string) {
|
||||
return await this.service.remove(id);
|
||||
}
|
||||
}
|
18
src/projects/projects.service.spec.ts
Normal file
18
src/projects/projects.service.spec.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ProjectsService } from './projects.service';
|
||||
|
||||
describe('ProjectsService', () => {
|
||||
let service: ProjectsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ProjectsService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ProjectsService>(ProjectsService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
35
src/projects/projects.service.ts
Normal file
35
src/projects/projects.service.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { BaseDbService } from 'src/commons/services/base-db.service';
|
||||
import { Repository } from 'typeorm';
|
||||
import { CreateProjectInput } from './dtos/create-project.input';
|
||||
import { Project } from './project.entity';
|
||||
|
||||
@Injectable()
|
||||
export class ProjectsService extends BaseDbService<Project> {
|
||||
readonly uniqueFields: Array<keyof Project> = ['name'];
|
||||
constructor(
|
||||
@InjectRepository(Project)
|
||||
readonly repository: Repository<Project>,
|
||||
) {
|
||||
super(repository);
|
||||
}
|
||||
|
||||
async list() {
|
||||
return this.repository.find();
|
||||
}
|
||||
|
||||
async create(dto: CreateProjectInput) {
|
||||
await this.isDuplicateEntity(dto);
|
||||
return await this.repository.save(this.repository.create(dto));
|
||||
}
|
||||
|
||||
async update(id: string, dto: CreateProjectInput) {
|
||||
await this.isDuplicateEntityForUpdate(id, dto);
|
||||
await this.repository.update({ id }, dto);
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
return (await this.repository.softDelete({ id })).affected;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user