DEV Community

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

Posted on

3 1

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 🔗

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay