ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

File Upload In GraphQL With Apollo Server Using S3 Bucket & Node.js

Home / Article & Blogs / Amazon S3 / File Upload In GraphQL With Apollo Server Using S3 Bucket & Node.js
By Mohammed Nadeem inAmazon S3

Graphql has become more common as a result of its various features which solve under/over fetching issues. Moreover, it enables simple caching, federation, non-versioning APIs, subscriptions, etc.

I studied numerous articles and instructions written by GraphQL community members on how to create GraphQL services. However, none of these resources stated that uploading a file was possible with GraphQL.

When I was assigned to manage and develop a new feature that involved Graphql file uploading, Then I spent nearly a week reading tonnes of tutorials, including those from the Apollo docs, GraphQL upload on GitHub, Google and stack-overflow, Although this feature was implemented in Apollo Server 2.0, I found that most of the resources on this feature were scattered across several repositories and tutorials leaving out critical steps.

This article will walk you through the steps required to set up a GraphQL server that can handle file upload in graphql and stream data into an S3 bucket

What is S3 Bucket?

A cloud hosting service offered by Amazon Web Services (AWS) is called Amazon S3 (Simple Storage Service) (AWS). It is a cloud-based storage solution that gives programmers and companies access to data, pictures, movies, and other information from anywhere at any time.

Many applications need to be able to upload files to an S3 bucket, and utilizing the Amazon SDK and the graphql upload middleware, this can be accomplished in a GraphQL Apollo Server with ease.

Installing the dependencies

Let’s install the following dependencies, I’ll use npm for this, but you sure can do this with the yarn command as well

npm install apollo-server apollo-server-express graphql-upload aws- sdk uuid

Amazon S3 configuration

The next step is to create an S3 bucket and set up the required IAM permissions so that your server can access the bucket. The AWS documentation contains detailed instructions on how to do this.

Now let’s begin with the setup of the S3 bucket

const AWS = require(“aws-sdk”);
module.exports = new AWS.S3({
credentials: {
// all secret keys should be kept in the env file.
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
region: process.env.AWS_BUCKET_REGION,
params: {
ACL: “public-read”,
Bucket: process.env.AWS_BUCKET_NAME,
},
},
app: {
storageDir: “tmp”,
});

Configure the Apollo server

This index.js file listens on port 4000 and contains an instance of ApolloServer with type definitions and resolvers.

const express = require(“express”);
const { ApolloServer } = require(“apollo-server-express”);
const { GraphQLUpload, graphqlUploadExpress } = require(“graphql-upload”);
const typeDefs = require(“./graphql/typeDefs/schema”);
const resolvers = require(“./graphql/resolvers/Query”);
const PORT = process.env.PORT; // 4000 port
async function startServer() {
// Error handling
const overrideError = (err) => {
if (err.message.startsWith(“Database Error: “)) {
return new Error(“Internal server error”);
}
return err;
};
const server = new ApolloServer({
typeDefs,
resolvers
});
await server.start();
const app = express();
app.use(graphqlUploadExpress());
server.applyMiddleware({ app });
await new Promise((r) => app.listen({ port: PORT }, r));
console.log(Server ready at http://localhost:${PORT}${server.graphqlPath});
} // http://localhost:4000/graphql
startServer();

Creating Graphql schema

const { gql } = require(“apollo-server”);
const typeDefs = gql` scalar Upload type File { status: Int! url: String! } type Mutation { uploadFile(files: Upload!): File } `;
module.exports = typeDefs

You might have noticed that we have defined a scalar named Upload in our schema. This scalar will be “mapped” to the implementation of the graphql upload requirement.

Now that our schema has been created, we can start creating our resolvers.

Upload file resolver

Let’s import the necessary modules and dependencies first.

const { GraphQLUpload} = require(“graphql-upload”); import { v4 as uuid } from ‘uuid’;
const s3 = require(“./config/awsS3/s3”);
module.exports = {
};

Next, we’ll map our scalar Upload to the implementation of graphql upload.

const { GraphQLUpload } = require(“graphql-upload”);
import { v4 as uuid } from ‘uuid”;
const s3 = require(“./config/awsS3/s3”);
module.exports = { Upload: GraphQLUpload
};

We can now begin working on our mutation, so we go to our arguments to obtain the file.

const { GraphQLUpload } = require(“graphql-upload”);
import { v4 as uuid } from ‘uuid’;
const s3 = require(“./config/awsS3/s3”);
module.exports = {
Upload: GraphQLUpload,
Mutation: {
uploadFile: async (_, { files }) => {
const unique = uuid() // generate random UUIDs.
const { createReadStream, filename, mimetype, encoding } = file;
const { Location } = await s3
.upload({
Body: createReadStream(),
Key: ${unique}/${filename},
ContentType: mimetype,
})
.promise();
return {
status: 200,
url: Location,
};
}
};

Testing your File/Image Upload

Alright. Now it’s time to have a taste of it. But wait file uploads are not supported by Apollo Playground’s Interface? So, you must test your File upload using Postman or you can also use the same thing with a curl command

curl –location –request POST ‘http://localhost:4000/graphql’ \
–form ‘operations=”{\”query\”: \”mutation ($files: Upload!) { uploadFile(files: $files) { status url } } \”, \”variables\”: {\”file\”: null}}”‘ \
–form ‘map=”{\”0\”: [\”variables.file\”]}”‘ \
–form ‘0=@”./images/mohd-nadeem.jpg”‘

Conclusion

With this approach, you can now upload files In GraphQl and access them with S3 URLs. I hope you found it interesting. If you noticed any errors in this article, please mention them in the comment sections

get in touch
Amazon S3Apollo ServerFile Upload In GraphQLGraphql uploadNodejs
24
Like this post
1 Post
Mohammed Nadeem

Search Posts

Archives

Categories

Recent posts

All About The OmniStudio FlexCards

All About The OmniStudio FlexCards

Boost Customer Experience With Repeater Widget in CRM Analytics

Boost Customer Experience With Repeater Widget in CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics

Net zero as a Service In CPG Industry

Net zero as a Service In CPG Industry

How Do We Import an External Library into Salesforce Lightning?

How Do We Import an External Library into Salesforce Lightning?

  • Data Retriever using Metadata API in Salesforce
    Previous PostData Retriever using Metadata API in Salesforce
  • Next PostHow Do We Import an External Library into Salesforce Lightning?
    Data Retriever using Metadata API in Salesforce

Related Posts

Upload files in Amazon S3 from Salesforce
Amazon S3 Apex Integration Salesforce

Upload files in Amazon S3 from Salesforce

Leave a Reply (Cancel reply)

Your email address will not be published. Required fields are marked *

*
*

ABSYZ Logo

INDIA | USA | UAE

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT