11import { forwardRef , Inject , Injectable , Logger } from '@nestjs/common' ;
22import { PrismaService } from '../prisma/prisma.service' ;
3- import { Build , Prisma , TestStatus } from '@prisma/client' ;
3+ import { Build , Prisma , TestStatus , Project } from '@prisma/client' ;
44import { TestRunsService } from '../test-runs/test-runs.service' ;
55import { EventsGateway } from '../shared/events/events.gateway' ;
66import { BuildDto } from './dto/build.dto' ;
77import { PaginatedBuildDto } from './dto/build-paginated.dto' ;
88import { ModifyBuildDto } from './dto/build-modify.dto' ;
9+ import { StaticService } from '../static/static.service' ;
910
1011@Injectable ( )
1112export class BuildsService {
@@ -15,7 +16,8 @@ export class BuildsService {
1516 private prismaService : PrismaService ,
1617 private eventsGateway : EventsGateway ,
1718 @Inject ( forwardRef ( ( ) => TestRunsService ) )
18- private testRunsService : TestRunsService
19+ private testRunsService : TestRunsService ,
20+ private staticService : StaticService
1921 ) { }
2022
2123 async findOne ( id : string ) : Promise < BuildDto > {
@@ -93,12 +95,38 @@ export class BuildsService {
9395 return build ;
9496 }
9597
96- async deleteOldBuilds ( projectId : string , keepBuilds : number ) {
97- keepBuilds = keepBuilds < 2 ? keepBuilds : keepBuilds - 1 ;
98- this . findMany ( projectId , undefined , keepBuilds ) . then ( ( buildList ) => {
99- buildList . data . forEach ( ( eachBuild ) => {
100- this . remove ( eachBuild . id ) ;
101- } ) ;
98+ async deleteOldBuilds ( project : Project ) {
99+ this . logger . log ( 'Going to delete old builds' ) ;
100+
101+ const keepBuilds = project . maxBuildAllowed <= 1 ? 1 : project . maxBuildAllowed - 1 ;
102+
103+ const buildsToDelete = await this . prismaService . build . findMany ( {
104+ where : { projectId : { equals : project . id } } ,
105+ orderBy : { createdAt : 'desc' } ,
106+ skip : keepBuilds ,
107+ } ) ;
108+
109+ const buildIds = buildsToDelete . map ( ( build ) => build . id ) ;
110+
111+ const testRunsToDelete = await this . prismaService . testRun . findMany ( { where : { buildId : { in : buildIds } } } ) ;
112+
113+ await this . prismaService . testRun . deleteMany ( { where : { buildId : { in : buildIds } } } ) ;
114+
115+ testRunsToDelete . forEach ( ( testRun ) => {
116+ this . staticService . deleteImage ( testRun . diffName ) ;
117+ this . staticService . deleteImage ( testRun . imageName ) ;
118+ } ) ;
119+
120+ testRunsToDelete . forEach ( ( testRun ) => {
121+ this . logger . log ( `TestRun deleted ${ testRun . id } ` ) ;
122+ this . eventsGateway . testRunDeleted ( testRun ) ;
123+ } ) ;
124+
125+ await this . prismaService . build . deleteMany ( { where : { id : { in : buildIds } } } ) ;
126+
127+ buildsToDelete . forEach ( ( build ) => {
128+ this . logger . log ( `Build deleted ${ build . id } ` ) ;
129+ this . eventsGateway . buildDeleted ( new BuildDto ( { ...build } ) ) ;
102130 } ) ;
103131 }
104132
0 commit comments