From d05a5d15512ab794ef80b31ef91090d5d88b3fcd Mon Sep 17 00:00:00 2001 From: matinzd Date: Thu, 31 Mar 2022 07:59:01 -0700 Subject: [PATCH] feat: add getAll function to formdata (#32444) Summary: The getAll() method of the [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) interface returns all the values associated with a given key from within a FormData object. ## Changelog [General] [Added] - Add getAll function to FormData class for getting all parts containing that key. This is also available in web API. Pull Request resolved: https://github.com/facebook/react-native/pull/32444 Test Plan: New test added in FormData-test.js Reviewed By: lunaleaps Differential Revision: D31798633 Pulled By: cortinico fbshipit-source-id: ef29bb54e930532a671adbe707be8d1a64ff0d82 --- Libraries/Network/FormData.js | 6 ++++ Libraries/Network/__tests__/FormData-test.js | 31 ++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/Libraries/Network/FormData.js b/Libraries/Network/FormData.js index 3392ada7e93edc..d1ec8116ad41b9 100644 --- a/Libraries/Network/FormData.js +++ b/Libraries/Network/FormData.js @@ -64,6 +64,12 @@ class FormData { this._parts.push([key, value]); } + getAll(key: string): Array { + return this._parts + .filter(([name]) => name === key) + .map(([, value]) => value); + } + getParts(): Array { return this._parts.map(([name, value]) => { const contentDisposition = 'form-data; name="' + name + '"'; diff --git a/Libraries/Network/__tests__/FormData-test.js b/Libraries/Network/__tests__/FormData-test.js index e8316b30b1a8a8..329fc0d4cca92c 100644 --- a/Libraries/Network/__tests__/FormData-test.js +++ b/Libraries/Network/__tests__/FormData-test.js @@ -77,4 +77,35 @@ describe('FormData', function () { }; expect(formData.getParts()[0]).toMatchObject(expectedPart); }); + + it('should return values based on the given key', function () { + formData.append('username', 'Chris'); + formData.append('username', 'Bob'); + + expect(formData.getAll('username').length).toBe(2); + + expect(formData.getAll('username')).toMatchObject(['Chris', 'Bob']); + + formData.append('photo', { + uri: 'arbitrary/path', + type: 'image/jpeg', + name: 'photo3.jpg', + }); + + formData.append('photo', { + uri: 'arbitrary/path', + type: 'image/jpeg', + name: 'photo2.jpg', + }); + + const expectedPart = { + uri: 'arbitrary/path', + type: 'image/jpeg', + name: 'photo2.jpg', + }; + + expect(formData.getAll('photo')[1]).toMatchObject(expectedPart); + + expect(formData.getAll('file').length).toBe(0); + }); });