-
-
Notifications
You must be signed in to change notification settings - Fork 517
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
Support "req.formData()" #1327
Comments
I am using a custom fetcher with // Intercept the upload
server.use(
rest.post(
"http://localhost:8000/fleetportalapi/graphiql",
(req, res, ctx) =>
res(
ctx.json({
data: {
fileUploadMileage: {
__typename: "FileUploadMileageError",
errorMessage: "Error parsing the CSV file.",
},
},
})
)
)
); This is not perfect - ideally I would be able to use
FWIW my custom fetch looks like this (mostly borrowed from import { extractFiles, isExtractableFile } from "extract-files";
const createRequestBody = <TVariables>(
query: string,
variables?: TVariables
) => {
const { files, clone } = extractFiles(
{ query, variables },
"",
isExtractableFile
);
if (files.size === 0) {
return JSON.stringify({ query, variables });
}
const form = new FormData();
form.append("operations", JSON.stringify(clone));
const map: { [key: number]: string[] } = {};
let i = 0;
files.forEach((paths) => {
map[++i] = paths;
});
form.append("map", JSON.stringify(map));
i = 0;
files.forEach((paths, file) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
form.append(`${++i}`, file as any);
});
return form as FormData;
};
export const useFetchData = <TData, TVariables>(
query: string,
options?: RequestInit["headers"]
): ((variables?: TVariables) => Promise<TData>) => {
return async (variables?: TVariables) => {
const body = createRequestBody(query, variables);
const res = await fetch(url, {
method: "POST",
headers: {
...(typeof body === "string"
? { "Content-Type": "application/json" }
: {}),
...(options ?? {}),
},
body,
});
const json = await res.json();
if (json.errors) {
const { message } = json.errors[0] || "Error..";
throw new Error(message);
}
return json.data;
};
}; My issue would be solved if |
@ddolcimascolo Can you provide reproduction code for this error? |
@95th I didn't forget, but facing some other troubles atm. If you want to give it a try it's really just
Was working fine in the previous minor. Cheers, |
@ddolcimascolo I tried this but its working fine for me. any special data included in the FormData? |
Nothing special. I'll definitely work on reproducing this in a repo |
Having same issue, can't pull file off with req.body.get("file"). Worked in previous versions.
Works in 0.43.1, stops working in 0.44.0+ |
Thx @nathanhannig. I didn't manage to create a full reproduction repo, yet. |
@95th @nathanhannig I finally created the reproduciton repo @ https://github.com/ddolcimascolo/msw-issue-1327 |
Guys, any news? |
@ddolcimascolo, no news so far. Anybody is welcome to take the reproduction repo above and step through this |
on 0.44.2 -> I can read FormData from Request data text() => gives the value of At some point it does seem like the file gets corrupted in 'upload' but I haven't gotten into where/how that could be improved/changed |
Can that corruption be related to #1158 somehow? |
Hi everyone, still no fix to this issue? We're stuck a few versions behind because of this... Cheers, |
I have been stuck at 0.43.1 because of this isse req.body was broken after that version (even though it incorrectly says it was depreciated) |
Welcome aboard 🙄 |
Hence why we've released it as a breaking change. It is getting deprecated, but it also drops some of the request reading methods since we didn't have the capacity to implement all of them.
I don't see why it wouldn't be. This is a scoped known change, and you have previous versions that supported this to verify your implementation against. How can I contribute?
The main task here is to determine how we used to handle Volunteers are certainly welcome. I will help with the code review so we could ship this feature in a timely manner. |
Hey guys, my tentative in #1422 |
@kettanaito Did you get a chance to review the PR? Cheers, |
Hey, @ddolcimascolo. Yes, thank you so much for opening it. I've left a few comments and I'd love to know your thoughts on those. Also, it's worth mentioning that #1404 change is going to introduce |
@kettanaito Thx for the feedback. I dropped Axios in favor of a raw XHR request but I have no clue how to handle your comment about FormData not existing in Node... |
I guess I stay on 0.38.1 until you implement the body getter... |
@boryscastor, the body getter is not coming back. Instead, in the next major release you will be able to read the request's body as form data like you would do in regular JavaScript: rest.post('/login', async ({ request }) => {
const data = await request.formData()
const email = data.get('email')
}) When is this coming out? Sometime this year, hopefully. When can I try this? You can try this right now. More details in #1464. |
what's the workaround until const arrayBuffer = await req.arrayBuffer();
const formData = undefined; // ??; |
@fibonacid, the const formData = new FormData()
formData.set('foo', 'bar')
const request = new Request('/url', { method: 'PUT', body: formData })
await request.text()
'------WebKitFormBoundaryY2WwRDBYmRbAKyLB\r\nContent-Disposition: form-data; name="foo"\r\n\r\nbar\r\n------WebKitFormBoundaryY2WwRDBYmRbAKyLB--\r\n' You can read the request body as text to obtain that string. Then, you can feed it to any parser that would turn it back into a You can use parse-multipart-data to parse that string into an object and then construct a Alternatively, consider switching to |
@kettanaito thanks, this is very helpful! |
Came across this thread after facing 2 issues with MSW - all my graphql handlers throwing input instance of arraybuffer whenever i used formdata, and |
Released: v2.0.0 🎉This has been released in v2.0.0! Make sure to always update to the latest version ( Predictable release automation by @ossjs/release. |
Prerequisites
Environment check
msw
versionNode.js version
16.13.0
Reproduction repository
https://github.com/ddolcimascolo/msw-issue-1327
Reproduction steps
Axios to send a POST request with a FormData body. Try to use req.body in the handler
Current behavior
Expected behavior
Maybe
req.formData()
as per https://developer.mozilla.org/en-US/docs/Web/API/Request/formData would be the way to go?The text was updated successfully, but these errors were encountered: