| 82 | } |
| 83 | |
| 84 | private handle(req: IncomingMessage, res: ServerResponse): void { |
| 85 | const chunks: Buffer[] = []; |
| 86 | req.on('data', (chunk: Buffer) => chunks.push(chunk)); |
| 87 | req.on('end', () => { |
| 88 | const body = Buffer.concat(chunks).toString('utf-8'); |
| 89 | const path = req.url ?? ''; |
| 90 | this.recorded.push({ |
| 91 | path, |
| 92 | method: req.method ?? '', |
| 93 | headers: req.headers as Record<string, string>, |
| 94 | body, |
| 95 | }); |
| 96 | const key = `${req.method} ${path}`; |
| 97 | const queue = this.responses.get(key); |
| 98 | const next = queue?.shift(); |
| 99 | if (!next) { |
| 100 | res.statusCode = 404; |
| 101 | res.end(JSON.stringify({ error: 'no fake response queued', key })); |
| 102 | return; |
| 103 | } |
| 104 | if (next.drop === true) { |
| 105 | // Destroy the socket so `fetch` rejects with a transport error. |
| 106 | req.socket.destroy(); |
| 107 | return; |
| 108 | } |
| 109 | res.statusCode = next.status; |
| 110 | res.setHeader('content-type', 'application/json'); |
| 111 | res.end(typeof next.body === 'string' ? next.body : JSON.stringify(next.body)); |
| 112 | }); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // ── Fixtures ────────────────────────────────────────────────────────── |