Compare commits

..

No commits in common. "f00f75673b8f02efce8fbd0937eecba9a1186ea8" and "e908d2981d6de7af784bac2f2451b74212b4f773" have entirely different histories.

12 changed files with 55 additions and 133 deletions

View File

@ -1,7 +1,6 @@
import { Field, ID, ObjectType } from '@nestjs/graphql'; import { Field, ID, ObjectType } from '@nestjs/graphql';
import { import {
CreateDateColumn, CreateDateColumn,
DeleteDateColumn,
PrimaryGeneratedColumn, PrimaryGeneratedColumn,
UpdateDateColumn, UpdateDateColumn,
} from 'typeorm'; } from 'typeorm';
@ -17,7 +16,4 @@ export class AppBaseEntity {
@UpdateDateColumn({ select: false }) @UpdateDateColumn({ select: false })
updatedAt: Date; updatedAt: Date;
@DeleteDateColumn({ select: false })
deletedAt?: Date;
} }

View File

@ -1,27 +1,55 @@
import { import {
ExceptionFilter,
Catch,
ArgumentsHost, ArgumentsHost,
Catch,
ExceptionFilter,
HttpException, HttpException,
HttpStatus,
} from '@nestjs/common'; } from '@nestjs/common';
import { ApolloError } from 'apollo-server-errors'; import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';
@Catch(HttpException) @Catch()
export class HttpExceptionFilter implements ExceptionFilter { export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) { catch(exception: any, host: ArgumentsHost) {
const message = exception.message; const ctx = host.switchToHttp();
const extensions: Record<string, any> = {}; const response = ctx.getResponse();
const err = exception.getResponse(); const request = ctx.getRequest();
if (typeof err === 'string') {
extensions.message = err; 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 { } else {
Object.assign(extensions, (err as any).extension); response.status(status).json({
extensions.message = (err as any).message; 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,
});
} }
return new ApolloError(
message,
exception.getStatus().toString(),
extensions,
);
} }
} }

View File

@ -1,15 +0,0 @@
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
import { sanitize } from '@neuralegion/class-sanitizer/dist';
@Injectable()
export class SanitizePipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
// console.log(value, typeof value);
if (value instanceof Object) {
value = Object.assign(new metadata.metatype(), value);
sanitize(value);
// console.log(value);
}
return value;
}
}

View File

@ -2,19 +2,11 @@ import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { HttpExceptionFilter } from './commons/filters/all.exception-filter';
import { SanitizePipe } from './commons/pipes/sanitize.pipe';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService); const configService = app.get(ConfigService);
app.useGlobalPipes(new SanitizePipe()); app.useGlobalPipes(new ValidationPipe());
app.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(configService.get<number>('http.port')); await app.listen(configService.get<number>('http.port'));
} }
bootstrap(); bootstrap();

View File

@ -1,7 +1,7 @@
import { InputType } from '@nestjs/graphql'; import { InputType } from '@nestjs/graphql';
import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model'; import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model';
import { import {
IsObject, IsInstance,
IsOptional, IsOptional,
IsString, IsString,
IsUUID, IsUUID,
@ -22,6 +22,6 @@ export class CreatePipelineInput {
name: string; name: string;
@IsOptional() @IsOptional()
@IsObject() @IsInstance(WorkUnitMetadata)
workUnitMetadata: WorkUnitMetadata; workUnitMetadata: WorkUnitMetadata;
} }

View File

@ -3,16 +3,9 @@ import { PipelinesResolver } from './pipelines.resolver';
import { PipelinesService } from './pipelines.service'; import { PipelinesService } from './pipelines.service';
import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmModule } from '@nestjs/typeorm';
import { Pipeline } from './pipeline.entity'; import { Pipeline } from './pipeline.entity';
import { BullModule } from '@nestjs/bull';
import { LIST_LOGS_TASK } from '../repos/repos.constants';
@Module({ @Module({
imports: [ imports: [TypeOrmModule.forFeature([Pipeline])],
TypeOrmModule.forFeature([Pipeline]),
BullModule.registerQueue({
name: LIST_LOGS_TASK,
}),
],
providers: [PipelinesResolver, PipelinesService], providers: [PipelinesResolver, PipelinesService],
}) })
export class PipelinesModule {} export class PipelinesModule {}

View File

@ -4,7 +4,6 @@ import { UpdatePipelineInput } from './dtos/update-pipeline.input';
import { Pipeline } from './pipeline.entity'; import { Pipeline } from './pipeline.entity';
import { PipelinesService } from './pipelines.service'; import { PipelinesService } from './pipelines.service';
import { ListPipelineArgs } from './dtos/list-pipelines.args'; import { ListPipelineArgs } from './dtos/list-pipelines.args';
import { LogList } from '../repos/dtos/log-list.model';
@Resolver() @Resolver()
export class PipelinesResolver { export class PipelinesResolver {
@ -42,9 +41,4 @@ export class PipelinesResolver {
async deletePipeline(@Args('id', { type: () => String }) id: string) { async deletePipeline(@Args('id', { type: () => String }) id: string) {
return await this.service.remove(id); return await this.service.remove(id);
} }
@Query(() => String)
async listLogsForPipeline(@Args('id', { type: () => String }) id: string) {
return await this.service.listLogsForPipeline(id);
}
} }

View File

@ -2,68 +2,25 @@ import { Test, TestingModule } from '@nestjs/testing';
import { PipelinesService } from './pipelines.service'; import { PipelinesService } from './pipelines.service';
import { Pipeline } from './pipeline.entity'; import { Pipeline } from './pipeline.entity';
import { getRepositoryToken } from '@nestjs/typeorm'; import { getRepositoryToken } from '@nestjs/typeorm';
import { getQueueToken } from '@nestjs/bull';
import { LIST_LOGS_TASK } from '../repos/repos.constants';
import { Repository } from 'typeorm';
import { Project } from '../projects/project.entity';
import { Job, Queue } from 'bull';
import { ListLogsOption } from '../repos/models/list-logs.options';
describe('PipelinesService', () => { describe('PipelinesService', () => {
let service: PipelinesService; let service: PipelinesService;
let repository: Repository<Pipeline>;
let pipeline: Pipeline;
let queue: Queue<ListLogsOption>;
beforeEach(async () => { beforeEach(async () => {
pipeline = Object.assign(new Pipeline(), {
id: 'test-pipeline',
name: 'pipeline',
branch: 'master',
projectId: 'test-project',
project: Object.assign(new Project(), {
id: 'test-project',
name: 'project',
} as Project),
} as Pipeline);
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
providers: [ providers: [
PipelinesService, PipelinesService,
{ {
provide: getRepositoryToken(Pipeline), provide: getRepositoryToken(Pipeline),
useValue: { useValue: {},
findOneOrFail: jest.fn().mockImplementation(() => pipeline),
},
},
{
provide: getQueueToken(LIST_LOGS_TASK),
useValue: {
add: jest.fn().mockImplementation(() => ({ id: 1 } as Job)),
},
}, },
], ],
}).compile(); }).compile();
service = module.get<PipelinesService>(PipelinesService); service = module.get<PipelinesService>(PipelinesService);
repository = module.get(getRepositoryToken(Pipeline));
queue = module.get(getQueueToken(LIST_LOGS_TASK));
}); });
it('should be defined', () => { it('should be defined', () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
describe('listLogsForPipeline', () => {
it('should send task to queue.', async () => {
const add = jest.spyOn(queue, 'add');
await expect(
service.listLogsForPipeline('test-pipeline'),
).resolves.toEqual(1);
expect(add).toBeCalledWith({
project: pipeline.project,
branch: pipeline.branch,
});
});
});
}); });

View File

@ -6,21 +6,13 @@ import { BaseDbService } from '../commons/services/base-db.service';
import { CreatePipelineInput } from './dtos/create-pipeline.input'; import { CreatePipelineInput } from './dtos/create-pipeline.input';
import { UpdatePipelineInput } from './dtos/update-pipeline.input'; import { UpdatePipelineInput } from './dtos/update-pipeline.input';
import { ListPipelineArgs } from './dtos/list-pipelines.args'; import { ListPipelineArgs } from './dtos/list-pipelines.args';
import { InjectQueue } from '@nestjs/bull';
import { LIST_LOGS_TASK } from '../repos/repos.constants';
import { Queue } from 'bull';
import { ListLogsOption } from '../repos/models/list-logs.options';
@Injectable() @Injectable()
export class PipelinesService extends BaseDbService<Pipeline> { export class PipelinesService extends BaseDbService<Pipeline> {
readonly uniqueFields: Array<Array<keyof Pipeline>> = [ readonly uniqueFields: Array<keyof Pipeline> = ['branch', 'projectId'];
['branch', 'projectId'],
];
constructor( constructor(
@InjectRepository(Pipeline) @InjectRepository(Pipeline)
readonly repository: Repository<Pipeline>, readonly repository: Repository<Pipeline>,
@InjectQueue(LIST_LOGS_TASK)
private readonly listLogsQueue: Queue<ListLogsOption>,
) { ) {
super(repository); super(repository);
} }
@ -42,16 +34,4 @@ export class PipelinesService extends BaseDbService<Pipeline> {
async remove(id: string) { async remove(id: string) {
return (await this.repository.softDelete({ id })).affected; return (await this.repository.softDelete({ id })).affected;
} }
async listLogsForPipeline(id: string) {
const pipeline = await this.repository.findOneOrFail({
where: { id },
relations: ['project'],
});
const job = await this.listLogsQueue.add({
project: pipeline.project,
branch: pipeline.branch,
});
return job.id;
}
} }

View File

@ -22,4 +22,7 @@ export class Project extends AppBaseEntity {
@Column({ nullable: true }) @Column({ nullable: true })
webHookSecret?: string; webHookSecret?: string;
@DeleteDateColumn()
deletedAt?: Date;
} }

View File

@ -1,5 +0,0 @@
import { Project } from '../../projects/project.entity';
export interface ListLogsOption {
project: Project;
branch: string;
}

View File

@ -1 +0,0 @@
export const LIST_LOGS_TASK = 'LIST_LOGS_TASK';