Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 19, 2021 05:58 am GMT

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}`));

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;

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;

Code of example in Github


Original Link: https://dev.to/nelsoncode/save-files-with-apollo-server-and-react-js-in-3-steps-58ad

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To