DEV Community

Cover image for Save files with Apollo Server and React JS in 3 steps
Nelson Adonis Hernández
Nelson Adonis Hernández

Posted on

Save files with Apollo Server and React JS in 3 steps

1. Backend with Express and Apollo Server

const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const app = express();
const { createWriteStream } = require("fs");
const cors = require("cors");

app.use(cors());

const typeDefs = gql`
  type Query {
    welcome: String
  }
  type Mutation {
    singleUpload(file: Upload): String
  }
`;

const saveImagesWithStream = ({ filename, mimetype, stream }) => {
  const path = `images/${filename}`;
  return new Promise((resolve, reject) =>
    stream
      .pipe(createWriteStream(path))
      .on("finish", () => resolve({ path, filename, mimetype }))
      .on("error", reject)
  );
};
const resolvers = {
  Query: {
    welcome: () => "Hello";
  },
  Mutation: {
    singleUpload: async (_, args) => {
      const { filename, mimetype, createReadStream } = await args.file;
      const stream = createReadStream();
      await saveImagesWithStream({ filename, mimetype, stream });
      return "success";
    },
  },
};

const server = new ApolloServer({ typeDefs: typeDefs, resolvers: resolvers });

server.applyMiddleware({ app });

app.listen({ port: 4000 }, () => console.log(`http://localhost:4000${server.graphqlPath}`));
Enter fullscreen mode Exit fullscreen mode

2. Setup Apollo Upload Client

import { ApolloProvider } from "@apollo/client";
import { client } from "./graphql/ApolloClient";
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { createUploadLink } from "apollo-upload-client";

function App() {
const link = createUploadLink({ uri: "http://localhost:4000/graphql" });

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});
  return (
    <div>
      <ApolloProvider client={client}>
        <h1>Hello</h1>
      </ApolloProvider>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Send Image with Apollo Client

import React, { useState } from "react";
import { useMutation, gql } from "@apollo/client";

function UploadImages() {
  const [newImage, setnewImage] = useState(null);
  const [uploadImage, { data }] = useMutation(gql`
    mutation singleUpload($file: Upload) {
      singleUpload(file: $file)
    }
  `);
  console.log(data);
  return (
    <div>
      <input type="file" onChange={(e) => setnewImage(e.target.files[0])} />
      <button
        onClick={() => {
          uploadImage({
            variables: {
              file: newImage,
            },
          });
        }}
      >
        SEND IMAGE
      </button>
    </div>
  );
}

export default UploadImages;
Enter fullscreen mode Exit fullscreen mode

Code of example in Github 🔗

Discussion (0)