Null values in object being converted to form send "null" to server

Open Beginner friendly
#485 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
65/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
typescript
Domain
api

Research direction

The issue points to a specific code block in the content-type handling for FormData. Look for the file containing the ContentType.FormData serializer, likely in a request builder or HTTP client module. The TODO comment indicates the exact line to modify. Test by creating a request with null/undefined values and verifying the FormData entries are omitted or empty strings, not 'null'/'undefined' strings.

Written by the indexing model from the issue text.

Description

When a request that uses the content type of ContentType.FormData is sent with a body, any null or undefined values in that object end up being sent to the server as 'null' or 'undefined' strings. This seems very wrong to make the server add special handling for strings containing the words null or undefined.

The code in question is this:

    [ContentType.FormData]: (input: any) =>
      Object.keys(input || {}).reduce((formData, key) => {
        const property = input[key];
        formData.append(
          key,
          property instanceof Blob
            ? property
            : typeof property === 'object' && property !== null
            ? JSON.stringify(property)
            : `${property}` // TODO: If property is null or undefined, this will result in 'null' or 'undefined'
        );
        return formData;
      }, new FormData()),

The line with the TODO shows the cause of the problem.
I see two ways of fixing this:

  1. Wrap the formData.append call in a conditional to only add it to the FormData object if the value is not null or undefined.
  2. Modify the line with the TODO so that it returns the empty string if property is null or undefined instead of blindly converting the value to a string.

To me, option 2 seems more correct since it's likely that purposefully setting a value to null or undefined may be a way of clearing a piece of data in the server; option 1 would not add the data to the form and thus wouldn't send the value to the server.

Dominant language
TypeScript
Stars
4.1k
Forks
436
Avg merge
9d 7h
Merged PRs (30d)
3

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from acacode/swagger-typescript-api

All issues in acacode/swagger-typescript-api

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.