apollo-upload-files
v7.1.0-alpha.1
Published
Enhances Apollo Client for intuitive file uploads via GraphQL mutations.
Downloads
1
Maintainers
Readme
apollo-upload-files
Enhances Apollo for intuitive file uploads via GraphQL queries or mutations. Use with a GraphQL multipart request spec server implementation, Where multipart requests are supported and operationName, query and variables are expected as request body context at the backend.
Setup
Install with peer dependencies using npm:
npm install apollo-upload-files apollo-link
Initialize Apollo Client with this terminating link:
import { createUploadLink } from 'apollo-upload-files'
const link = createUploadLink(/* Options */)
Options
createUploadLink
options match createHttpLink
options:
includeExtensions
(boolean): Toggles sendingextensions
fields to the GraphQL server. (default:false
).uri
(string): GraphQL endpoint URI (default:/graphql
).credentials
(string): OverridesfetchOptions.credentials
.headers
(object): Merges with and overridesfetchOptions.headers
.fetchOptions
(object):fetch
init; overridden by upload requirements.fetch
(function): Fetch API to use (default: Globalfetch
).
Usage
Use FileList
, File
, Blob
or ReactNativeFile
instances anywhere within query or mutation input variables to send a GraphQL multipart request.
Example
Consider a situation where you need to create a user and upload it's resume. following mutation is what you would give to the apollo instance.
mutation createUser ($username: String!, $password: String!)
{
createUser(username: $username, password: $password)
{
user
{
id
}
}
}
And this is what you would give to mutate function as input.
apollo.mutate({
mutation: CREATE_USER_MUTATION ,
variables: {
username: username,
password: password,
resume: userResumeFile
}
})
As you can see it is only needed to provide the file (in this case our resume) to the 'variables' field of mutate input object, and not to the actual CREATE_USER_MUTATION constant itself.
It is possible to change the name of file/files in the request, you just need to replace 'resume' key in variables object in the mutate function (in the example given) with whatever you want.
the resume given to the mutate function can be an array of files, in this case for each file, an index is appended to the key of file (in this case 'resume') -> resume_1, resume_2, ... .
Support
- Node.js v6.10+, see
package.json
engines
. - Browsers >1% usage, see
package.json
browserslist
. - Angular >= 2.
- React Native.