1+ import express , { Request , Response } from 'express'
2+ import { Queue } from 'bullmq'
3+
4+ export function createServer ( queue : Queue ) {
5+ const app = express ( )
6+ app . use ( express . json ( { limit : '2mb' } ) )
7+
8+ app . post ( '/scan' , async ( req : Request , res : Response ) => {
9+ const payload = req . body || { }
10+ const isLarge = JSON . stringify ( payload ) . length > 200_000 || payload ?. large === true
11+ const job = await queue . add ( 'scan' , { payload, isLarge } , { removeOnComplete : true , removeOnFail : true } )
12+ res . status ( 202 ) . json ( { jobId : job . id , statusUrl : `/scan/${ job . id } /status` , resultUrl : `/scan/${ job . id } /result` } )
13+ } )
14+
15+ app . get ( '/scan/:id/status' , async ( req : Request , res : Response ) => {
16+ const id = req . params . id
17+ const job = await queue . getJob ( id )
18+ if ( ! job ) {
19+ res . status ( 404 ) . json ( { error : 'not_found' } )
20+ return
21+ }
22+ const state = await job . getState ( )
23+ const progress = job . progress || 0
24+ res . json ( { state, progress } )
25+ } )
26+
27+ app . get ( '/scan/:id/result' , async ( req : Request , res : Response ) => {
28+ const id = req . params . id
29+ const job = await queue . getJob ( id )
30+ if ( ! job ) {
31+ res . status ( 404 ) . json ( { error : 'not_found' } )
32+ return
33+ }
34+ const state = await job . getState ( )
35+ if ( state !== 'completed' ) {
36+ res . status ( 202 ) . json ( { state } )
37+ return
38+ }
39+ const result = job . returnvalue
40+ res . json ( { result } )
41+ } )
42+
43+ return app
44+ }
0 commit comments