I need to read a locally stored image, embed the image to a form with form-data using the GraphQL multipart request specification, then perform a POST request to a graphql server with the body of the request being the form data itself.
I read the image using fs.readFile, and use the data as an argument to my post data function:
fs.readFile('./location/to/image/image.jpg', (err, data) => {
if (err) {
throw (err);
}
postData(data);
});
My postData function goes as follows:
function postData(readable) {
/** Create form data */
const requestBody = new FormData();
/** Define the query */
const sdl = `
mutation ($image: Upload!) {
testUpload(image: $image){
code
success
message
}
}
`;
/** Follow instructions according to graphql multipart request specification
* https://github.com/jaydenseric/graphql-multipart-request-spec */
requestBody.append(
'operations',
JSON.stringify({
query: sdl,
variables: { image: null },
})
);
requestBody.append(
'map',
JSON.stringify({
0: ['variables.image'],
})
);
requestBody.append('0', readable);
/** Submit the form */
return new Promise((resolve, reject) => {
requestBody.submit('http://localhost:4000/api/graphql', (err, res) => {
if (err) {
console.error(err);
reject(err);
} else {
let body = '';
res.on('readable', () => {
body += res.read();
});
res.on('end', () => {
resolve(JSON.parse(body));
});
}
});
});
}
What happens is, I successfully hit my API and my resolver, but the file's mimetype is received as application/octet-stream.
I am assumming that I am not reading the data correctly, or something else entirely.
I would truely appreciate any help. Thank you.