Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is an example of how to upload a file using Apollo Server v4 and graphql-upload:

  1. Install graphql-upload package by running the following command in your project directory:
npm install graphql-upload
  1. In your Apollo Server setup (usually in your index.js or server.js file), import the GraphQLUpload object from graphql-upload package:
const { GraphQLUpload } = require("graphql-upload");
  1. In your Apollo Server schema, add a custom scalar for files using GraphQLUpload:
const typeDefs = `
  scalar Upload

  type Mutation {
    uploadFile(file: Upload!): String!
  }
`;
  1. In your Apollo Server resolver, add a resolver for your new uploadFile mutation:
const resolvers = {
  Mutation: {
    uploadFile: async (parent, { file }) => {
      const { createReadStream, filename, mimetype } = await file;
      const stream = createReadStream();
      // Handle file stream
      return `File ${filename} uploaded successfully`;
    },
  },
};
  1. In your Apollo Server instantiation, add the plugins option that includes graphqlUploadExpress() middleware:
const { ApolloServer } = require("apollo-server-express");
const { graphqlUploadExpress } = require("graphql-upload");

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [graphqlUploadExpress()],
});
  1. In your client, create a FormData object to pass the file to your server:
const fileInput = document.querySelector("#fileInput");
const formData = new FormData();
formData.append("file", fileInput.files[0]);
  1. In your client, execute the uploadFile mutation with the formData object:
const response = await fetch("/graphql", {
  method: "POST",
  headers: { "Content-type": "application/json" },
  body: JSON.stringify({
    query: `
      mutation uploadFile($file: Upload!) {
        uploadFile(file: $file)
      }
    `,
    variables: { file: formData.get("file") },
  }),
});
const data = await response.json();
console.log(data);

That's it! You should now be able to upload files using Apollo Server v4 and graphql-upload.