Skip to content

Commit

Permalink
Fixed form mapper error where File objects were not being mapped corr…
Browse files Browse the repository at this point in the history
…ectly (#448)

* Fixed form mapper error where File objects were not being mapped correctly

Will now rely on `FormData` methods for catching erroneous objects being passed in - it may be worth working towards a more robust mapper for future use, but for now, it is felt that this version is more than suitable for our needs.

* Removed log statement

Missed a log statement that is no longer required - this has been removed
  • Loading branch information
droberts-ctrlo authored Aug 7, 2024
1 parent c5c9599 commit bbbc201
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 29 deletions.
21 changes: 0 additions & 21 deletions src/frontend/js/lib/util/mapper/formdataMapper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,6 @@ describe("Basic formdata mapper tests", () => {
expect(formdataMapper(data)).toEqual(formData);
});

it("should map a nested object", () => {
const data = {
name: "John Doe",
age: 30,
email: "[email protected]",
address: {
street: "1234 Elm St",
city: "Springfield",
state: "IL"
}
};
const formData = new FormData();
formData.append("name", "John Doe");
formData.append("age", "30");
formData.append("email", "[email protected]");
formData.append("address_street", "1234 Elm St");
formData.append("address_city", "Springfield");
formData.append("address_state", "IL");
expect(formdataMapper(data)).toEqual(formData);
});

it("should throw an error for nested objects deeper than one layer", () => {
const data = {
name: "John Doe",
Expand Down
9 changes: 1 addition & 8 deletions src/frontend/js/lib/util/mapper/formdataMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,7 @@ export const formdataMapper = <T>(data: FormData | T) => {
if(data instanceof Object && Object.keys(data).length === 0) throw new Error("Cannot map an empty object");
const formData = new FormData();
Object.entries(data).forEach(([key, value]) => {
if (value instanceof Object) {
Object.entries(value).forEach(([subKey, subValue]) => {
if(subValue instanceof Object) throw new Error("Nested objects deeper than one layer are not supported");
formData.append(`${key}_${subKey}`, subValue as string);
});
} else {
formData.append(key, value as string);
}
formData.append(key, value);
});
return formData;
}

0 comments on commit bbbc201

Please sign in to comment.