From 4fe80e3fcc9fa71d25e5cdc27ae50890010e7797 Mon Sep 17 00:00:00 2001 From: Eitan Levi Date: Sun, 8 Sep 2019 17:24:44 -0700 Subject: [PATCH] [request] Specify types allowed for Multipart body (#38190) The request library allows anything to be put in a Multipart body as long as it can be passed to `Buffer.from()`: https://github.com/request/request/blob/master/lib/multipart.js#L74 However the current implementation allows only `string` to be used as the multipart body. In my use-case I needed to pass a `Buffer` instance directly. This change defines a type alias for `MultipartBody` that includes `string`, `Buffer`, `ArrayBuffer` or `UInt8Array`. --- types/request/index.d.ts | 4 +++- types/request/request-tests.ts | 38 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index c18f97554f..951eff12e3 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -183,6 +183,8 @@ declare namespace request { type OptionsWithUrl = UrlOptions & CoreOptions; type Options = OptionsWithUri | OptionsWithUrl; + type MultipartBody = string | Buffer | ArrayBuffer | Uint8Array; + type RequestCallback = (error: any, response: Response, body: any) => void; interface HttpArchiveRequest { @@ -204,7 +206,7 @@ declare namespace request { chunked?: boolean; data?: Array<{ 'content-type'?: string, - body: string + body: MultipartBody }>; } diff --git a/types/request/request-tests.ts b/types/request/request-tests.ts index 64b74cf023..e6b97f4f93 100644 --- a/types/request/request-tests.ts +++ b/types/request/request-tests.ts @@ -649,6 +649,44 @@ request( } ); +request( + { + method: 'PUT', + uri: 'http://mikeal.iriscouch.com/testjs/' + rand, + multipart: { + data: [ + { + 'content-type': 'application/json; charset=utf-8', + body: JSON.stringify({ + _attachments: { + 'dot.png': { + follows: true, + length: 269, + content_type: 'image/png', + }, + }, + }), + }, + { + 'content-type': 'image/png', + body: Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAA3NCSVQICAjb4U/gAAAAX3pUWHRSYXcgcHJvZmlsZSB0eXBlIEFQUDEAAAiZ40pPzUstykxWKCjKT8vMSeVSAANjEy4TSxNL' + + 'o0QDAwMLAwgwNDAwNgSSRkC2OVQo0QAFmJibpQGhuVmymSmIzwUAT7oVaBst2IwAAAAWSURBVAiZY/z//z8DAwMTAwMDAwMDACQGAwGaMKL7AAAAAElFTkSuQmCC', + ), + }, + ], + }, + }, + (error, response, body) => { + if (response.statusCode === 201) { + console.log('image saved as http://mikeal.iriscouch.com/testjs/' + rand); + } else { + console.log('error: ' + response.statusCode); + console.log(body); + } + }, +); + request( { method: 'GET' , uri: 'http://www.google.com'