Ask Your Question
4

What is the procedure for uploading a file using Apollo Server v4 and graphql-upload?

asked 2023-01-21 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-08-28 17:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-21 11:00:00 +0000

Seen: 12 times

Last updated: Aug 28 '22