| 8 | ) => { |
| 9 | const transport = { |
| 10 | request(options: Record<string, any>, onResponse: (res: PassThrough) => void) { |
| 11 | const chunks: Buffer[] = []; |
| 12 | |
| 13 | const req = new Writable({ |
| 14 | write(chunk, _encoding, callback) { |
| 15 | chunks.push(Buffer.from(chunk)); |
| 16 | callback(); |
| 17 | }, |
| 18 | }) as Writable & Record<string, any>; |
| 19 | |
| 20 | req.destroyed = false; |
| 21 | req.setTimeout = () => {}; |
| 22 | req.write = req.write.bind(req); |
| 23 | req.destroy = () => { |
| 24 | req.destroyed = true; |
| 25 | return req; |
| 26 | }; |
| 27 | req.close = req.destroy; |
| 28 | const originalEnd = req.end.bind(req); |
| 29 | req.end = (...args: unknown[]) => { |
| 30 | originalEnd(...(args as Parameters<Writable['end']>)); |
| 31 | |
| 32 | const body = Buffer.concat(chunks); |
| 33 | const response = responseFactory ? responseFactory(body, options) : {}; |
| 34 | |
| 35 | const res = new PassThrough() as PassThrough & Record<string, any>; |
| 36 | res.statusCode = response.statusCode ?? 200; |
| 37 | res.statusMessage = response.statusMessage ?? 'OK'; |
| 38 | res.headers = response.headers ?? { 'content-type': 'application/json' }; |
| 39 | res.req = req; |
| 40 | |
| 41 | onResponse(res); |
| 42 | res.end(response.body ?? JSON.stringify({ ok: true })); |
| 43 | |
| 44 | return req; |
| 45 | }; |
| 46 | |
| 47 | return req; |
| 48 | }, |
| 49 | }; |
| 50 | |
| 51 | return { transport }; |