| 255 | * (this is done automatically after 30 seconds if you don't, but if you're sending a lot of requests its better to do it yourself) |
| 256 | */ |
| 257 | export class Response { |
| 258 | body?: AsyncReadCloser; |
| 259 | headers: Record<string, string>; |
| 260 | statusCode: number; |
| 261 | |
| 262 | constructor(statusCode: number, headers: Record<string, string>, body?: AsyncReadCloser) { |
| 263 | this.statusCode = statusCode; |
| 264 | this.headers = headers; |
| 265 | this.body = body; |
| 266 | } |
| 267 | |
| 268 | /** |
| 269 | * Read the entire response body and return the raw Uint8Array for it. |
| 270 | */ |
| 271 | async readAll(): Promise<Uint8Array> { |
| 272 | if (!this.body) { |
| 273 | throw new Error("no response body") |
| 274 | } |
| 275 | |
| 276 | let curBuffer = new Uint8Array(); |
| 277 | let readBuf = new Uint8Array(1024 * 10); |
| 278 | |
| 279 | while (true) { |
| 280 | const n = await this.body.read(readBuf); |
| 281 | const newBuffer = new Uint8Array(curBuffer.length + n); |
| 282 | newBuffer.set(curBuffer, 0); |
| 283 | newBuffer.set(readBuf.slice(0, n), curBuffer.length); |
| 284 | curBuffer = newBuffer; |
| 285 | |
| 286 | if (n === 0) { |
| 287 | break; |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | return curBuffer; |
| 292 | } |
| 293 | |
| 294 | /** |
| 295 | * Read and decode the response body as json |
| 296 | */ |
| 297 | async json<T>(): Promise<T> { |
| 298 | let fullBody = decodeText(await this.readAll()); |
| 299 | return JSON.parse(fullBody); |
| 300 | } |
| 301 | |
| 302 | /** |
| 303 | * Read and decode the reponse body as utf8 encoded text |
| 304 | */ |
| 305 | async text(): Promise<string> { |
| 306 | let buf = await this.readAll(); |
| 307 | return decodeText(buf); |
| 308 | } |
| 309 | } |
| 310 | } |
nothing calls this directly
no outgoing calls
no test coverage detected