(logFile: string, fsModule: FsLike)
| 48 | * Accepts POST requests with LogBody JSON, appends formatted lines to logFile. |
| 49 | */ |
| 50 | export function createLogMiddleware(logFile: string, fsModule: FsLike) { |
| 51 | const logDir = logFile.split('/').slice(0, -1).join('/'); |
| 52 | |
| 53 | return (req: IncomingMessage, res: ServerResponse, _next: () => void) => { |
| 54 | if (req.method !== 'POST') { |
| 55 | res.writeHead(405); |
| 56 | res.end(); |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | const chunks: Buffer[] = []; |
| 61 | req.on('data', (chunk: Buffer) => chunks.push(chunk)); |
| 62 | req.on('end', () => { |
| 63 | try { |
| 64 | const body: LogBody = JSON.parse(Buffer.concat(chunks).toString()); |
| 65 | const line = formatLogLine(body); |
| 66 | if (!fsModule.existsSync(logDir)) { |
| 67 | fsModule.mkdirSync(logDir, { recursive: true }); |
| 68 | } |
| 69 | fsModule.appendFileSync(logFile, line + '\n', 'utf8'); |
| 70 | res.writeHead(204); |
| 71 | res.end(); |
| 72 | } catch { |
| 73 | res.writeHead(400); |
| 74 | res.end(); |
| 75 | } |
| 76 | }); |
| 77 | }; |
| 78 | } |
no test coverage detected