A file upload seems like a mutation. It's often accompanied by other data. But it's a big binary blob, so I'm not sure how GraphQL can deal with it. How would you integrate file uploads into an app built with Relay?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
I found an explanation in the docs. You can subclass Relay.Mutation and implement the getFiles function.
Also, express-graphql provides an example in its test cases of how to handle this on the server side.
First you need to write the Relay update in your frontend component. Like this:
And then follow by implementing the mutation on the frontend:
And last, implement the handler on the server/schema.
All the code above you can find them in my repo https://github.com/bfwg/relay-gallery There is also a live demo https://fanjin.io
I am merely sharing the findings of Marc-Andre Giroux from his blog, which is Rails-specific, so I will try to make it more generic, and providing the details of the answer provided by @Nick.
There are 2 parts:
Client-side Javascript Code
The client-side code further consists of 2 parts:
The mutation to upload file, which extends Relay.Mutation (UploadFileMutation)
The component that contains the React component (FileUploader) to render the UI for selecting the file, and calls the mutation to do the upload
Server-side Server-Specific Code
The server-side code also consists of 2 parts:
For NodeJS Express server (extracted from express-graqphl test cases as pointed out by @Nick):
Similarly, for a non-JS server, e.g., RubyOnRails:
For Javascript GraphQL Schema:
For Rails GraphQL Schema:
To add to the other answers, with Relay Modern, there was a small change on how you should send the files from the client. Instead of having a
getFiles
in your mutation and passing the files to the constructor, you can use something like the following:The
uploadables
config option is kinda of hidden, since there is no mention to it on the docs, but it can be found here: https://github.com/facebook/relay/blob/c4430643002ec409d815366b0721ba88ed3a855a/packages/relay-runtime/mutations/commitRelayModernMutation.js#L32