Skip to main content

Upload Files With GraphQL, Apollo, and React-Native

React-Native: we need extra component: RNFetchBlob
With React-Native, it’s a little bit more complicated. It boils down to intercepting the outgoing request and changing it to be a multi-part form and injecting the file blob.
To trigger the action, you can include a special flag in your mutation that tells the code to treat the variable “file” as a file to upload.




in ReactJS web app we only need do this, because with web sites, browser helps out with setting up a multi-part form request.

Front end:

uploadFileToAndmap({
variables: {
file: photos[0]
}
})
.then(async ({ data }) => {})
.catch(error => setMessage(error.message))


GraphQL API:

uploadFileToAndmap: combineResolvers(
// isAuthenticated,
async (parent, args, { models }) => {
const { file } = await args
const { createReadStream, filename, mimetype, encoding } = await file
const stream = createReadStream()
const result = await RestAPI.uploadFileToAndmap(filename, stream)
return result
}
),

Comments

Popular posts from this blog

About GraphQL - Downside

Web caching complexity

File uploading. Since GraphQL doesn’t understand files, a file uploading feature is not included in its specification. You won’t have to deal with this limitation in case of REST, as there you can POST or PUT whatever content you want to.
To allow file uploads in your GraphQL web app, there are several options: using Base64 encoding. But it will make the request larger and expensive to encode/decode.making a separate API endpoint just for this purpose.using a library like Apollo for implementing the GraphQL multipart request specification.uploadFileToS3:combineResolvers( // isAuthenticated, async (parent, args, { models }) => { const { file } = awaitargs const { createReadStream, filename, mimetype, encoding } = awaitfile conststream = createReadStream() constresult = awaituploadFileToS3(filename, stream) returnresult } ),