How to upload a file through Apollo Server v4 and graphql-upload?

1.4k views Asked by At

im using Apollo server v4 with expressjs and NEXTJS for my Frontend. What I want is to create a Mutation like uploadFile using upload-graphql to upload a file to my Backend Server.

backend_server

upload type

export interface Upload {
    filename: string;
    mimetype: string;
    encoding: string;
    createReadStream: () => Stream;
  }

my mutation:

@Mutation(() => Boolean)
  async uploadFile(
    @Arg("picture", () => GraphQLUpload)
    { createReadStream, filename }: Upload
  ): Promise<boolean> {
    return new Promise(async (resolve, reject) =>
      createReadStream()
        .pipe(createWriteStream(__dirname + `/../../../images/${filename}`))
        .on("finish", () => resolve(true))
        .on("error", () => reject(false))
    );
  }
}

but the problem is, whenever I upload something like a photo, I get ApolloError: Argument Validation Error .

I think, there is no way to upload through new Version of Apollo server (v4) yet, but if anyone knows about it, please help me !

my dependencies

"dependencies":{
   "@apollo/server": "^4.3.1",     
   "express": "^4.18.2",
   "graphql": "^16.6.0",     
   "graphql-fields": "^2.0.3",     
   "graphql-middleware": "^6.1.33",     
   "graphql-scalars": "^1.20.1",     
   "graphql-shield": "^7.6.5",     
   "graphql-upload": "14",     
   "type-graphql": "2.0.0-beta.1",   },

I tried to upload a file on my frontend nextjs - apollo-upload-client.

and front-end upload Scenario

enter image description here

code_of_front_end

front-end-app-config

It's just a hobby project, and I know there are alternatives to kind of use other approach to upload files => like extra endpoint api or using like s3, but I want to get my files uploaded through graphql.

1

There are 1 answers

0
NicoSan On

As requested, here a piece of code based on your sources (not tested), but you should add "Apollo-Require-Preflight" header into createUploadLink for it works

export const client = new ApolloClient({
    link: createUploadLink({
         headers: {"Apollo-Require-Preflight": "true"},
    }),
    cache: new InMemoryCache(),
});