Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modifying FormData body in beforeRequest hook does not work #645

Open
stevensacks opened this issue Oct 11, 2024 · 2 comments
Open

Modifying FormData body in beforeRequest hook does not work #645

stevensacks opened this issue Oct 11, 2024 · 2 comments

Comments

@stevensacks
Copy link

stevensacks commented Oct 11, 2024

I wanted to snake case my FormData beforeRequest. The ky-hooks-change-case library only works with non-FormData. So, I wrote my own.

export const snakeCaseBody = (original) => {
  if (original instanceof FormData) {
    const body = new FormData();

    [...original.keys()].forEach((key) => {
      body.set(snakeCase(key), original.get(key)!);
    });

    return body;
  }

  return JSON.stringify(toSnakeCase(JSON.parse(original)));
};

export const requestToSnakeCase = async (request, options) => {
  if (options.body) {
    const body = snakeCaseBody(options.body);

    return new Request(request, {body});
  }
};

I've got a unit test that proves snakeCaseBody works. I also logged the Content-Type header of the request and it looks correct:

Content-Type multipart/form-data; boundary=----formdata-undici-066001922265

But on the receiving end of the API, I get an error that the body cannot be parsed as FormData.

Is this a limitation in ky, or am I doing something wrong?

@sholladay
Copy link
Collaborator

As long as the boundary is correct, I would expect it to work. We've had problems with that before.

@stevensacks
Copy link
Author

stevensacks commented Oct 13, 2024

Ok thanks. I’ll keep experimenting and see if I can figure it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants