<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: kingmaker9841</title>
    <description>The latest articles on Forem by kingmaker9841 (@kingmaker9841).</description>
    <link>https://forem.com/kingmaker9841</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F473179%2F27136b92-9206-4104-a4f4-d46b086993cc.jpeg</url>
      <title>Forem: kingmaker9841</title>
      <link>https://forem.com/kingmaker9841</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kingmaker9841"/>
    <language>en</language>
    <item>
      <title>Apollo-server-express File Upload on Local Storage and on AWS S3</title>
      <dc:creator>kingmaker9841</dc:creator>
      <pubDate>Tue, 29 Sep 2020 09:52:29 +0000</pubDate>
      <link>https://forem.com/kingmaker9841/apollo-server-express-file-upload-on-local-storage-and-on-aws-s3-1km8</link>
      <guid>https://forem.com/kingmaker9841/apollo-server-express-file-upload-on-local-storage-and-on-aws-s3-1km8</guid>
      <description>&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt; : We will be uploading files from one storage to another. I will use express, apollo-server-express and aws-sdk.&lt;/p&gt;

&lt;p&gt;File Upload is fundamental to web-apps. And there is not much information regarding details of file uploads using apollo-server-express for beginner and intermediate. So, anyone reading this post, if you do not understand some code, please feel free to comment and I will update you asap. Now, let us write some code...&lt;/p&gt;

&lt;p&gt;First initialize &lt;code&gt;package.json&lt;/code&gt; in your working directory using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let us install some module.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express apollo-server-express dotenv nodemon uuid aws-sdk
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are not familiar with some of the modules, you can google the module name and learn from its documentation.&lt;/p&gt;

&lt;p&gt;Open &lt;code&gt;package.json&lt;/code&gt; and make some changes as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, &lt;code&gt;app.js&lt;/code&gt; is my server file but you can rename it to anything you want.&lt;br&gt;
If your &lt;code&gt;main:&lt;/code&gt; property is &lt;code&gt;app.js&lt;/code&gt; then go ahead and create a file named &lt;code&gt;app.js&lt;/code&gt; in your working directory.Also create a file &lt;code&gt;.env&lt;/code&gt; in order to store some environment variables. Now inside &lt;code&gt;app.js&lt;/code&gt;, paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const app = express();
const {ApolloServer} = require('apollo-server-express');
require('dotenv').config();

let server = new ApolloServer({
    typeDefs, resolvers
});
server.applyMiddleware({app});

let PORT = process.env.PORT || 5000;
app.listen(PORT, ()=&amp;gt;{
    console.log(`Server started on ${PORT}...`);
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will get our server up and running on port 5000.&lt;br&gt;
Now configure your AWS S3 bucket to get &lt;code&gt;accesskeyid&lt;/code&gt;, &lt;code&gt;secretaccesskey&lt;/code&gt;, &lt;code&gt;region&lt;/code&gt; and &lt;code&gt;bucket-name&lt;/code&gt;. Then create a directory named &lt;code&gt;config&lt;/code&gt; and inside it create a file &lt;code&gt;s3.js&lt;/code&gt; and copy the code below:&lt;br&gt;
&lt;em&gt;s3.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const aws = require('aws-sdk');

let s3 = new aws.S3({
    credentials: {
        accessKeyId: process.env.ACCESS_KEY_ID,
        secretAccessKey: process.env.SECRET_ACCESS_KEY
    },
    region: process.env.REGION,
    params : {
        ACL : 'public-read',
        Bucket : process.env.AWS_BUCKET
    }
});

module.exports = s3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, all the environment variables are kept inside &lt;code&gt;.env&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Now create a directory named &lt;code&gt;schema&lt;/code&gt; and create two files namely &lt;code&gt;typedefs.js&lt;/code&gt; and &lt;code&gt;resolvers.js&lt;/code&gt; and paste the following code:&lt;br&gt;
&lt;em&gt;typedefs.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const {gql} = require('apollo-server-express')

const typedefs = gql`
    type Query {
        uploadedFiles : [File]
    }
    type Mutation {
        singleUploadLocal (file: Upload!) : File
        multipleUploadLocal (files: [Upload]!) : [File]
        singleUploadS3 (file : Upload!) : File
        multipleUploadS3 (files : [Upload]!) : [File]
    }
    type File {
        success : String!
        message : String!
        mimetype : String
        encoding : String
        filename : String
        location : String
    }
`;
module.exports = typedefs;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;resolvers.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fs = require('fs');
const {v4: uuid} = require('uuid');
const s3 = require('../config/s3');

const processUpload = async (file)=&amp;gt;{
    const {createReadStream, mimetype, encoding, filename} = await file;
    let path = "uploads/" + uuid() + filename;
    let stream = createReadStream();
    return new Promise((resolve,reject)=&amp;gt;{
        stream
        .pipe(fs.createWriteStream(path))
        .on("finish", ()=&amp;gt;{

            resolve({
                success: true,
                message: "Successfully Uploaded",
                mimetype, filename, encoding, location: path
            })
        })
        .on("error", (err)=&amp;gt;{
            console.log("Error Event Emitted")
            reject({
                success: false,
                message: "Failed"
            })
        })
    })
}

let processUploadS3 = async (file)=&amp;gt;{
    const {createReadStream, mimetype, encoding, filename} = await file;
    let stream = createReadStream();
    const {Location} = await s3.upload({
        Body: stream,
        Key: `${uuid()}${filename}`,
        ContentType: mimetype
    }).promise();
    return new Promise((resolve,reject)=&amp;gt;{
        if (Location){
            resolve({
                success: true, message: "Uploaded", mimetype,filename,
                location: Location, encoding
            })
        }else {
            reject({
                success: false, message: "Failed"
            })
        }
    })
}
const resolvers = {
    Mutation: {
        singleUploadLocal : async (_, args)=&amp;gt;{
            return processUpload(args.file);
        },
        multipleUploadLocal : async (_, args) =&amp;gt;{
            let obj =  (await Promise.all(args.files)).map(processUpload);
            console.log(obj);
            return obj;
        },
        singleUploadS3 : async (_, args)=&amp;gt;{
            return processUploadS3(args.file);
        },
        multipleUploadS3 : async (_, args)=&amp;gt;{
            let obj = (await Promise.all(args.files)).map(processUploadS3);
            return obj;
        }
    }
}

module.exports = resolvers;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now to test it out, I am using a chrome extension called &lt;code&gt;Altair&lt;/code&gt; that allows me to easily upload file on my graphql query which looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F6h7wr69em9lmeax1dhoz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F6h7wr69em9lmeax1dhoz.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can find the code above in my github repo:&lt;br&gt;
&lt;a href="https://github.com/kingmaker9841/apollo-multiple-upload" rel="noopener noreferrer"&gt;https://github.com/kingmaker9841/apollo-multiple-upload&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Have a great day!
&lt;/h1&gt;

</description>
      <category>apolloserverexpress</category>
      <category>aws</category>
      <category>express</category>
      <category>fileupload</category>
    </item>
  </channel>
</rss>
