|
| 1 | +import { Request, Response, NextFunction } from 'express'; |
| 2 | + |
| 3 | +type AbortFunction = () => void; |
| 4 | + |
| 5 | +export const getRequestId = (req: Request): string => { |
| 6 | + const requestId = req.headers['x-request-id']?.toString().split(','); |
| 7 | + return requestId?.[0] ?? ''; |
| 8 | +}; |
| 9 | + |
| 10 | +export class AbortableService { |
| 11 | + private abortRegistries = new Map<string, AbortFunction | null>(); |
| 12 | + |
| 13 | + private registerAbortableFunction = ( |
| 14 | + requestId: string, |
| 15 | + abortFn: AbortFunction |
| 16 | + ): void => { |
| 17 | + this.abortRegistries.set(requestId, abortFn); |
| 18 | + }; |
| 19 | + |
| 20 | + public abort = ( |
| 21 | + requestId: string, |
| 22 | + { deletable = true }: { deletable?: boolean } = {} |
| 23 | + ): boolean => { |
| 24 | + const abortFn = this.abortRegistries.get(requestId) ?? null; |
| 25 | + |
| 26 | + if (abortFn) { |
| 27 | + abortFn(); |
| 28 | + |
| 29 | + if (deletable) { |
| 30 | + this.abortRegistries.delete(requestId); |
| 31 | + } |
| 32 | + |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + return false; |
| 37 | + }; |
| 38 | + |
| 39 | + public expressMiddleware = ( |
| 40 | + req: Request, |
| 41 | + res: Response, |
| 42 | + next: NextFunction |
| 43 | + ) => { |
| 44 | + const requestId = getRequestId(req); |
| 45 | + |
| 46 | + console.log('MIDDLEWARE', this.abortRegistries); |
| 47 | + |
| 48 | + if (!requestId) { |
| 49 | + return next(); |
| 50 | + } |
| 51 | + |
| 52 | + if (this.abortRegistries.has(requestId)) { |
| 53 | + this.abort(requestId, { deletable: false }); |
| 54 | + } |
| 55 | + |
| 56 | + const controller = new AbortController(); |
| 57 | + |
| 58 | + (req as any).controller = controller; |
| 59 | + (req as any).signal = controller.signal; |
| 60 | + |
| 61 | + this.registerAbortableFunction(requestId, () => { |
| 62 | + controller.abort(new Error('AbortError')); |
| 63 | + }); |
| 64 | + |
| 65 | + req.on('close', () => { |
| 66 | + if (!res.writableEnded) { |
| 67 | + console.log('requestId', requestId); |
| 68 | + this.abort(requestId); |
| 69 | + } |
| 70 | + }); |
| 71 | + |
| 72 | + next(); |
| 73 | + }; |
| 74 | +} |
0 commit comments