Skip to content

FormData in a POST request #240

@thekevinscott

Description

@thekevinscott

Hi! I'm trying to POST against a REST endpoint that uploads a file as part of a FormData object. From what I can tell, apollo-link-rest transforms FormData objects into {} prior to sending.

There's a few issues somewhat similar (like this) but the resolutions don't seem to work for me.

From what I can tell, this particular bit destroys an incoming FormData object and returns a blank object ({}). If I change line 615 like so:

// FileList/File are only available in some browser contexts
  // Notably: *not available* in react-native.
  if (
    ((global as any).FileList && object instanceof FileList) ||
    ((global as any).File && object instanceof File) ||
    object instanceof FormData) // <----- new line
  ) {
    // Object is a FileList or File object => no keys to convert!
    return object;
  }

With the following gql:

mutation UpdateDocument(
  $payload: any!
) {
  updateDocument(payload: $payload) @rest(
    type: "File"
    path: "/documents"
    method: "POST"
    bodyKey: "payload"
    bodySerializer: $transform,
  ) {
    NoResponse
  }
}

And the following JS:

import UPLOAD_DOCUMENT from './updateDocument.gql';

...

const [uploadDocument] = useMutation(UPLOAD_DOCUMENT);

const payload = new FormData();
payload.append('file', file, file.name);
uploadDocument({
  variables: {
    payload,
    // we need the transform function to again prevent `body` from turning into a `{}`
    transform: (body: FormData, headers: Headers) => ({
      body,
      headers,
    }),
  },
});

Then things appear to work fine. But I'm not sure if I'm missing something key here - there doesn't seem to be much documentation around file uploads (I notice you ask in the other issue for help providing documentation - I'd be happy to if I understood what to do!)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement💡featureFeature: new addition or enhancement to existing solutions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions