Apollo-link-rest: Is it possible to submit file objects with apollo-link-rest?

Created on 11 Nov 2019  ·  5Comments  ·  Source: apollographql/apollo-link-rest

An example query:

  mutation register {
    register(
      input: {
        email: $email
        avatar: $avatar
        password: $password
      }
    ) @rest(type: "Register", path: "auth/register", method: "POST")
  }

The form has a file input which send's a File object (this is the avatar property). When logging the avatar variable I can see this property is defined, however when sending the data with apollo-link-rest the file object becomes empty.

Logging the variable before sending the mutation:
image

When sending the data to the server via apollo the object is empty:

image

I could not find any mention of uploading files in the doc's so I am not sure if it's something that is possible.

help wanted 🛠 question❔

All 5 comments

I believe this is possible, as we had to fix some bugs related to mangling File objects.

That said, I haven’t used this recently, as I use Apollo-link-rest on react-native.

You may have to read through our source to debug this and figure out why it might not be working! It’s possible that the real fix is in Apollo-client not Apollo-link-rest!

Thanks for the reply! I mainly wanted to check I was not missing something obvious, like a setting that needs to be enabled, or a link that needs to be added :slightly_smiling_face:

For example I have seen some people mention that apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client) is required for file uploads in regular apollo.

I am not sure if a similar link needs to be added to the client in apollo-link-rest?

No, that doesn’t apply here.

As recently as July, somebody posted an example of react File upload using apollo-link-rest.

Maybe this helps?

https://github.com/apollographql/apollo-link-rest/issues/200#issuecomment-509287597

If you figure it out, maybe we should write a doc section about how to do this!

Thank you so much @fbartho!

That issue helped solve the problem, the key changes I had to make were adding the file encode method to the bodySerializers

bodySerializers: {
    fileEncode: (data: any, headers: Headers) => {
      const formData = new FormData()
      formData.append('file', data, data.name)
      headers.set('Accept', '*/*')
      return { body: formData, headers }
    }
  }

And also the part where you specify the serialiser on the query

@rest(
        type: "File"
        path: "YOUR_API_URL"
        method: "POST"
        bodySerializer: "fileEncode"
      ) {

It would be super helpful if something like this was in the docs. Thanks again!

Was this page helpful?
0 / 5 - 0 ratings