I have a working Apollo-Graphql Node.js server running with express middleware. Queries and Mutations, including file upload mutation, work fine from connecting front end clients and when called from functions run in Node and passed via axios requests -- except for the file upload mutations.
I've tested using the same query and file paths in Firecamp, and tried variations of passing and checking the file path / doing my best to confirm that the directory structure is getting parsed accurately. This is the error code returned with the axios response (I broke up the response for config.data from console output):
response: {
status: 400,
statusText: 'Bad Request',
headers: {
'x-powered-by': 'Express',
'access-control-allow-origin': '*',
'content-type': 'application/json; charset=utf-8',
'content-length': '1424',
etag: 'W/"590-jNRKeEwYD1b3Cxa/bjf3qp7npHg"',
date: 'Fri, 11 Dec 2020 22:36:12 GMT',
connection: 'close'
},
config: {
url: 'http://localhost:4002/graphql',
method: 'post',
data: '{
"query":"mutation singleUpload($file: Upload!) {
singleUpload(file: $file) {
filename
mimetype
encoding
}
}",
"variables":{"file":"../bulkImports/testPenThumbnail.png"}
}',`
The query definition and function call to axios:
const UPLOAD_FILE = gql`
mutation singleUpload($file: Upload!) {
singleUpload(file: $file) {
filename
mimetype
encoding
}
}
`
export function uploadFile(endpoint) {
const file = '../bulkImports/testPenThumbnail.png';
axios.post(endpoint, {
query: print(UPLOAD_FILE),
variables: { file } })
.then(res => console.dir(res.data))
.catch(err => console.error(err));
}
And the resolver for singleUpload
singleUpload(parent, args) {
return args.file.then(file => {
const { createReadStream, filename, mimetype, encoding } = file;
const stream = createReadStream();
const pathName = join(__dirname, `../../testUploads/${filename}`);
stream.pipe(createWriteStream(pathName));
return {
filename,
mimetype,
encoding,
};
});
}
From other errors/debugging along the way, my best guess is that the upload mutation is only seeing the file path as an ordinary String and not parsing it as an Upload scalar -- and that I should be looking at using the fs module to send more in the way of file object data/stream? I've tried a few things using fs methods, but node/back-end is still pretty new to me and I'm not really sure if I'm even barking up the right tree for how the Upload scalar is constructed.
Of course I'm happy to post any more config or error details that would help -- and thanks in advance to everyone who can help me make sense of this or improve the code below!
(oh, and the intended use-case for calling this from a server will be for bulk uploading records to populate a new db collection; besides just trying to learn more about back-end/node/axios/graphql basics...)