| 197 | * @param {{ limit: number }} options |
| 198 | */ |
| 199 | export function rewriteJsonResponse(transform, { limit }) { |
| 200 | return (proxyRes, req, res) => { |
| 201 | const status = proxyRes.statusCode ?? 502; |
| 202 | const headers = { ...proxyRes.headers }; |
| 203 | const encoding = headers["content-encoding"]; |
| 204 | const isJson = /\bapplication\/json\b/i.test(headers["content-type"] ?? ""); |
| 205 | if ( |
| 206 | !isJson || |
| 207 | req.method === "HEAD" || |
| 208 | (encoding && encoding !== "identity") |
| 209 | ) { |
| 210 | res.writeHead(status, headers); |
| 211 | proxyRes.pipe(res); |
| 212 | return; |
| 213 | } |
| 214 | const chunks = []; |
| 215 | let size = 0; |
| 216 | let streaming = false; |
| 217 | proxyRes.on("data", (chunk) => { |
| 218 | if (streaming) return; |
| 219 | size += chunk.length; |
| 220 | if (size <= limit) { |
| 221 | chunks.push(chunk); |
| 222 | return; |
| 223 | } |
| 224 | streaming = true; |
| 225 | res.writeHead(status, headers); |
| 226 | for (const buffered of chunks.splice(0)) res.write(buffered); |
| 227 | res.write(chunk); |
| 228 | proxyRes.pipe(res); |
| 229 | }); |
| 230 | proxyRes.on("end", () => { |
| 231 | if (streaming) return; |
| 232 | let body = Buffer.concat(chunks); |
| 233 | try { |
| 234 | body = Buffer.from( |
| 235 | JSON.stringify(transform(JSON.parse(body.toString("utf8")))), |
| 236 | ); |
| 237 | } catch { |
| 238 | // Not JSON after all; pass it through as received. |
| 239 | } |
| 240 | delete headers["transfer-encoding"]; |
| 241 | headers["content-length"] = String(body.length); |
| 242 | res.writeHead(status, headers); |
| 243 | res.end(body); |
| 244 | }); |
| 245 | }; |
| 246 | } |
| 247 | |
| 248 | function once(fn) { |
| 249 | let called = false; |