ember-graphql / ember-apollo-client

🚀 An ember-cli addon for Apollo Client and GraphQL
MIT License
279 stars 72 forks source link

Question: Ember Apollo Client and file uploads #401

Closed DirkLachowski closed 3 years ago

DirkLachowski commented 3 years ago

I tried to use ember apollo client with apollo-file-upload, but had zero success. Any examples/hints?

josemarluedke commented 3 years ago

Hi @DirkLachowski! I have a working app with apollo-upload-client.

I created a separate service for apollo that extends my default apollo service, this service replaces the apollo link with the apollo-upload-client.

Here is the code:

import Apollo from 'my-app/pods/apollo/service';
import { createUploadLink, LinkOptions } from 'apollo-upload-client';
import { ApolloLink } from '@apollo/client/core';
import { setContext } from '@apollo/client/link/context';
import { isPresent } from '@ember/utils';

export default class ApolloUpload extends Apollo {
  public link(): ApolloLink {
    const { apiURL, requestCredentials } = this.options;
    const linkOptions: LinkOptions = { uri: apiURL, fetch };

    if (isPresent(requestCredentials)) {
      linkOptions.credentials = requestCredentials;
    }

    const uploadLink = createUploadLink(linkOptions);

    const authLink = setContext((): object => {
      return { headers: this.getHeaders() };
    });

    return authLink.concat(uploadLink);
  }
}

// DO NOT DELETE: this is how TypeScript knows how to look up your services.
declare module '@ember/service' {
  interface Registry {
    'apollo-upload': ApolloUpload;
  }
}

Please ignore all the auth stuff. I hope this helps.