Reputation: 41
I am looking for a package which I can use for uploading files via graphql mutation using apollo-angular package. Also, can anyone help me understand which format will the file be uploaded and fetched to and from the server?
Thanks for your time.
Upvotes: 3
Views: 3088
Reputation: 296
In your server schema you need to define the file argument as type Upload. This is a built in type provided by Apollo. However if you do get errors about type Upload just add it as a custom Scalar type.
const { gql } = require('apollo-server');
const TypeDef = gql `
scalar Upload
type Mutation {
upload(file: Upload!)
}
`
In your revolvers you can access the file in your args, One thing to note is that the file will be a promise;
const resolver = {
Mutation: {
async upload(obj, args, context, info) {
const file = await args.file;
// ... DO STUFF
},
}
}
The package you are looking for for uploading files is the apollo-angular-link-http
package. Within the query context you need to set useMultipart to true.
So a file upload request should look something like this.
// The Mutation Query Using Type of 'Upload' to represent the file
const uploadFileMutation = gql`
mutation UploadMutation($file: Upload!) {
upload(file: $file) {
YOUR RESPONSE
}
}
}
// The Apollo Client request
// Context of 'useMultipart' needs to be set to true to enable file upload
this.Apollo.mutate<any>({
mutation: uploadFileMutation,
variables: {
file: this.file
},
context: {
useMultipart: true
}
}).subscribe(({ data }) => {
this.response = data.upload
});
Upvotes: 4