Reputation: 119
I am trying to upload files with Angular Apollo as Client and Apollo 2.0 as Server.
Trust me, I tried every tutorial, example I could find on the internet but no help. There's a library called apollo-upload-file they have given an example of how to implement it but at the client side they have used React. Although I tried implementing his example but nothing works.
Please help.
Upvotes: 7
Views: 4066
Reputation: 296
In your schema you need to define the file argument as type Upload this is a built in type provided by Apollo
const { gql } = require('apollo-server');
const TypeDef = gql `
type Mutation {
upload(file: Upload!)
}
`
If you are getting an error about type Upload not being a type you can also define it in your schema ( I had this issue )
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
},
}
}
In the client you need to use the apollo-angular-link-http
package to help with file uploads.
In the context
of the request use need to set useMultipart : true
Query will look something like this
const uploadFileMutation = gql`
mutation UploadMutation(
$file: Upload!
) {
upload(file: $file) {
YOUR RESPONSE
}
}
}
`
The Apollo request will look like this
constructor(
private Apollo: Apollo
) { }
fileUpload(file){
this.Apollo.mutate<any>({
mutation: uploadFileMutation,
variables: {
file: this.file
},
context: {
useMultipart: true
}
}).subscribe(({ data }) => {
this.response = data.upload
});
}
I hope this helps or at least gets you on the right track.
Upvotes: 18