Compare commits
3 Commits
e908d2981d
...
f00f75673b
Author | SHA1 | Date | |
---|---|---|---|
|
f00f75673b | ||
|
bba7963949 | ||
|
bf4590bd4c |
@ -1,6 +1,7 @@
|
||||
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||
import {
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
@ -16,4 +17,7 @@ export class AppBaseEntity {
|
||||
|
||||
@UpdateDateColumn({ select: false })
|
||||
updatedAt: Date;
|
||||
|
||||
@DeleteDateColumn({ select: false })
|
||||
deletedAt?: Date;
|
||||
}
|
||||
|
@ -1,55 +1,27 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
Catch,
|
||||
ArgumentsHost,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';
|
||||
import { ApolloError } from 'apollo-server-errors';
|
||||
|
||||
@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,
|
||||
});
|
||||
@Catch(HttpException)
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: HttpException, host: ArgumentsHost) {
|
||||
const message = exception.message;
|
||||
const extensions: Record<string, any> = {};
|
||||
const err = exception.getResponse();
|
||||
if (typeof err === 'string') {
|
||||
extensions.message = err;
|
||||
} 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,
|
||||
});
|
||||
Object.assign(extensions, (err as any).extension);
|
||||
extensions.message = (err as any).message;
|
||||
}
|
||||
return new ApolloError(
|
||||
message,
|
||||
exception.getStatus().toString(),
|
||||
extensions,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
15
src/commons/pipes/sanitize.pipe.ts
Normal file
15
src/commons/pipes/sanitize.pipe.ts
Normal file
@ -0,0 +1,15 @@
|
||||
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;
|
||||
}
|
||||
}
|
10
src/main.ts
10
src/main.ts
@ -2,11 +2,19 @@ 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);
|
||||
const configService = app.get(ConfigService);
|
||||
app.useGlobalPipes(new ValidationPipe());
|
||||
app.useGlobalPipes(new SanitizePipe());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
await app.listen(configService.get<number>('http.port'));
|
||||
}
|
||||
bootstrap();
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { InputType } from '@nestjs/graphql';
|
||||
import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model';
|
||||
import {
|
||||
IsInstance,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
@ -22,6 +22,6 @@ export class CreatePipelineInput {
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInstance(WorkUnitMetadata)
|
||||
@IsObject()
|
||||
workUnitMetadata: WorkUnitMetadata;
|
||||
}
|
||||
|
@ -3,9 +3,16 @@ import { PipelinesResolver } from './pipelines.resolver';
|
||||
import { PipelinesService } from './pipelines.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Pipeline } from './pipeline.entity';
|
||||
import { BullModule } from '@nestjs/bull';
|
||||
import { LIST_LOGS_TASK } from '../repos/repos.constants';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Pipeline])],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Pipeline]),
|
||||
BullModule.registerQueue({
|
||||
name: LIST_LOGS_TASK,
|
||||
}),
|
||||
],
|
||||
providers: [PipelinesResolver, PipelinesService],
|
||||
})
|
||||
export class PipelinesModule {}
|
||||
|
@ -4,6 +4,7 @@ import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
||||
import { Pipeline } from './pipeline.entity';
|
||||
import { PipelinesService } from './pipelines.service';
|
||||
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
||||
import { LogList } from '../repos/dtos/log-list.model';
|
||||
|
||||
@Resolver()
|
||||
export class PipelinesResolver {
|
||||
@ -41,4 +42,9 @@ export class PipelinesResolver {
|
||||
async deletePipeline(@Args('id', { type: () => String }) id: string) {
|
||||
return await this.service.remove(id);
|
||||
}
|
||||
|
||||
@Query(() => String)
|
||||
async listLogsForPipeline(@Args('id', { type: () => String }) id: string) {
|
||||
return await this.service.listLogsForPipeline(id);
|
||||
}
|
||||
}
|
||||
|
@ -2,25 +2,68 @@ import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PipelinesService } from './pipelines.service';
|
||||
import { Pipeline } from './pipeline.entity';
|
||||
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', () => {
|
||||
let service: PipelinesService;
|
||||
let repository: Repository<Pipeline>;
|
||||
let pipeline: Pipeline;
|
||||
let queue: Queue<ListLogsOption>;
|
||||
|
||||
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({
|
||||
providers: [
|
||||
PipelinesService,
|
||||
{
|
||||
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();
|
||||
|
||||
service = module.get<PipelinesService>(PipelinesService);
|
||||
repository = module.get(getRepositoryToken(Pipeline));
|
||||
queue = module.get(getQueueToken(LIST_LOGS_TASK));
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -6,13 +6,21 @@ import { BaseDbService } from '../commons/services/base-db.service';
|
||||
import { CreatePipelineInput } from './dtos/create-pipeline.input';
|
||||
import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
||||
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()
|
||||
export class PipelinesService extends BaseDbService<Pipeline> {
|
||||
readonly uniqueFields: Array<keyof Pipeline> = ['branch', 'projectId'];
|
||||
readonly uniqueFields: Array<Array<keyof Pipeline>> = [
|
||||
['branch', 'projectId'],
|
||||
];
|
||||
constructor(
|
||||
@InjectRepository(Pipeline)
|
||||
readonly repository: Repository<Pipeline>,
|
||||
@InjectQueue(LIST_LOGS_TASK)
|
||||
private readonly listLogsQueue: Queue<ListLogsOption>,
|
||||
) {
|
||||
super(repository);
|
||||
}
|
||||
@ -34,4 +42,16 @@ export class PipelinesService extends BaseDbService<Pipeline> {
|
||||
async remove(id: string) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -22,7 +22,4 @@ export class Project extends AppBaseEntity {
|
||||
|
||||
@Column({ nullable: true })
|
||||
webHookSecret?: string;
|
||||
|
||||
@DeleteDateColumn()
|
||||
deletedAt?: Date;
|
||||
}
|
||||
|
5
src/repos/models/list-logs.options.ts
Normal file
5
src/repos/models/list-logs.options.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { Project } from '../../projects/project.entity';
|
||||
export interface ListLogsOption {
|
||||
project: Project;
|
||||
branch: string;
|
||||
}
|
1
src/repos/repos.constants.ts
Normal file
1
src/repos/repos.constants.ts
Normal file
@ -0,0 +1 @@
|
||||
export const LIST_LOGS_TASK = 'LIST_LOGS_TASK';
|
Loading…
Reference in New Issue
Block a user