@@ -4,11 +4,13 @@ import { DEFAULT_LOCALE, HEADERS } from "#constants";
44import { localStore } from "#store" ;
55import { parseErrorMessage } from "#utils/error" ;
66import { createMiddlewaresPipelineRequestHandler } from "#utils/middleware-utils" ;
7+ import { handlePurge , type HandlePurge } from "./handlers/handle-purge" ;
78import { handleStaticFileRoute } from "./handlers/handle-static-file-route" ;
89import { router } from "./router" ;
910import { translations_enGB } from "./translations/en-gb" ;
1011import type {
1112 AuthService ,
13+ PurgeHandlerOptions ,
1214 RequestHandler ,
1315 RequestHandlerOptions ,
1416 StoryBookerUser ,
@@ -32,7 +34,6 @@ export function createRequestHandler<User extends StoryBookerUser>(
3234 options : RequestHandlerOptions < User > ,
3335) : RequestHandler {
3436 const logger = options . logger || console ;
35-
3637 const initPromises = Promise . allSettled ( [
3738 options . auth ?. init ?.( { } ) . catch ( logger . error ) ,
3839 options . database . init ?.( { } ) . catch ( logger . error ) ,
@@ -89,3 +90,42 @@ export function createRequestHandler<User extends StoryBookerUser>(
8990
9091 return requestHandler ;
9192}
93+
94+ /**
95+ * Callback to create a purge-handler based on provided options.
96+ * Purging deletes all builds older than certain days based on Project's configuration.
97+ *
98+ * Note: The latest build on project's default branch is not deleted.
99+ */
100+ export function createPurgeHandler ( options : PurgeHandlerOptions ) : HandlePurge {
101+ const logger = options . logger || console ;
102+ const initPromises = Promise . allSettled ( [
103+ options . database . init ?.( { } ) . catch ( logger . error ) ,
104+ options . storage . init ?.( { } ) . catch ( logger . error ) ,
105+ ] ) ;
106+
107+ return async ( ...params : Parameters < HandlePurge > ) => {
108+ // Make sure initialisations are complete before first request is handled.
109+ await initPromises ;
110+
111+ try {
112+ localStore . enterWith ( {
113+ abortSignal : params [ 1 ] . abortSignal ,
114+ database : options . database ,
115+ errorParser : options . errorParser ,
116+ locale : DEFAULT_LOCALE ,
117+ logger : params [ 1 ] ?. logger ?? logger ,
118+ prefix : "/" ,
119+ request : new Request ( "" ) ,
120+ storage : options . storage ,
121+ translation : translations_enGB ,
122+ url : "/" ,
123+ user : null ,
124+ } ) ;
125+
126+ await handlePurge ( ...params ) ;
127+ } catch ( error ) {
128+ logger . error ( parseErrorMessage ( error , options . errorParser ) . errorMessage ) ;
129+ }
130+ } ;
131+ }
0 commit comments