|
| 1 | +import { Request, Response, NextFunction, Express } from 'express'; |
| 2 | +import { AbortFunction } from './request-interruption-service.types'; |
| 3 | +import { getRequestId, setRequestMeta } from './request-interruption-service.utils'; |
| 4 | + |
| 5 | +class RequestInterruptionService { |
| 6 | + private abortRegistries = new Map<string, AbortFunction | null>(); |
| 7 | + |
| 8 | + private registerAbortableFunction = (requestId: string, abortFn: AbortFunction): void => { |
| 9 | + this.abortRegistries.set(requestId, abortFn); |
| 10 | + }; |
| 11 | + |
| 12 | + public abort = (requestId: string, { deletable = true }: { deletable?: boolean } = {}): boolean => { |
| 13 | + const abortFn = this.abortRegistries.get(requestId) ?? null; |
| 14 | + |
| 15 | + if (abortFn) { |
| 16 | + abortFn(); |
| 17 | + |
| 18 | + if (deletable) { |
| 19 | + this.abortRegistries.delete(requestId); |
| 20 | + } |
| 21 | + |
| 22 | + return true; |
| 23 | + } |
| 24 | + |
| 25 | + return false; |
| 26 | + }; |
| 27 | + |
| 28 | + public expressMiddleware = (req: Request, res: Response, next: NextFunction): void => { |
| 29 | + const requestId = getRequestId(req); |
| 30 | + |
| 31 | + if (!requestId) { |
| 32 | + return next(); |
| 33 | + } |
| 34 | + |
| 35 | + if (this.abortRegistries.has(requestId)) { |
| 36 | + this.abort(requestId, { deletable: false }); |
| 37 | + } |
| 38 | + |
| 39 | + const controller = new AbortController(); |
| 40 | + |
| 41 | + setRequestMeta(req, controller); |
| 42 | + |
| 43 | + this.registerAbortableFunction(requestId, () => { |
| 44 | + controller.abort(new Error('AbortError')); |
| 45 | + }); |
| 46 | + |
| 47 | + req.on('close', () => { |
| 48 | + if (!res.writableEnded) { |
| 49 | + this.abort(requestId); |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | + next(); |
| 54 | + }; |
| 55 | +} |
| 56 | + |
| 57 | +export const initRequestInterruptionService = ( |
| 58 | + app: Express, |
| 59 | + { basePath = '', endpointName = '/api/cancel' }: { basePath?: string; endpointName?: string } = {} |
| 60 | +) => { |
| 61 | + const requestInterruptionService = new RequestInterruptionService(); |
| 62 | + |
| 63 | + app.use(requestInterruptionService.expressMiddleware); |
| 64 | + |
| 65 | + app.post(`${basePath}${endpointName}`, (req, res) => { |
| 66 | + const requestId = getRequestId(req); |
| 67 | + |
| 68 | + if (requestId && requestInterruptionService.abort(requestId)) { |
| 69 | + res.status(499).json({ cancelled: true }); |
| 70 | + } else { |
| 71 | + res.status(404).json({ error: 'Request not found' }); |
| 72 | + } |
| 73 | + }); |
| 74 | +}; |
0 commit comments