DEV Community

Cover image for GraphQL Image Upload To Cloudinary
Duru Chidozie
Duru Chidozie

Posted on

GraphQL Image Upload To Cloudinary

A comprehensive guide on how to upload image to cloudinary using graphql.

As you know, i love to explain things in such a way newbies can understand also.So please pardon me if you feel like this is way below your level.

Prerequisites

  1. NodeJs must be installed on your machine.
  2. You must have signed up with Cloudinary.

Project Structure

project
|   node_modules/
│   .env    
│   app.js
|   package.json
|   yarn-error.log
|   yarn.lock 
Enter fullscreen mode Exit fullscreen mode

Let's Begin

let's initialize our server with yarn

yarn init
Enter fullscreen mode Exit fullscreen mode
The above code sets up our server with ready packages.Next,we need to install the necessary node modules for our server.

let's install the necessary node modules:

  • express - Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

  • nodemon - Nodemon is a tool that monitors our app for changes and restarts our server.

  • apollo-server-express - This is the Express and Connect integration of GraphQL Server.

  • dotenv - This loads environment variables from a .env file into process.env.

  • cloudinary - This would serve as our cloud storage service for easily uploading images.

yarn add express, apollo-server-express, dotenv, nodemon and cloudinary
Enter fullscreen mode Exit fullscreen mode

By now your project structure should look like this:

project
|   node_modules/
|   package.json
|   yarn-error.log
|   yarn.lock 
Enter fullscreen mode Exit fullscreen mode

We need to create two new files .env and app.js.Immediately after creating these files your project structure should look like the first project structure in this article.

Now, we are going to write our environment variables to our .env file

PORT = 4000
CLOUDINARY_API_KEY=your_cloudinary_api_key
CLOUDINARY_API_SECRET=your_cloudinary_api_secret
CLOUDINARY_NAME=your_cloudinary_name
Enter fullscreen mode Exit fullscreen mode

If you do not have a cloudinary account,you will need to create one in two easy steps and get your cloudinary credentials:
Sign up
Account Verification

Next we are going to write into our app.js file which we previously created.

//import our necessary node modules
require("dotenv").config();
const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const cloudinary = require("cloudinary");
//get port from  process.env which is set to 4000 
const { PORT } = process.env;

const app = express();

const typeDefs = gql`
  type Query {
    _: Boolean
  }
/*our mutation type for image upload which accepts the image location as a string whether local or remote.It returns a string.
*/
  type Mutation {
    uploadPhoto(photo: String): String
  }
`;
const resolvers = {
  Mutation: {
    uploadPhoto: async (_, { photo }) => {
//initialize cloudinary
      cloudinary.config({
        cloud_name: process.env.CLOUDINARY_NAME,
        api_key: process.env.CLOUDINARY_API_KEY,
        api_secret: process.env.CLOUDINARY_API_SECRET,
      });
/*
try-catch block for handling actual image upload
*/
      try {
        const result = await cloudinary.v2.uploader.upload(photo, {
//here i chose to allow only jpg and png upload
          allowed_formats: ["jpg", "png"],
//generates a new id for each uploaded image
          public_id: "",
/*creates a folder called "your_folder_name" where images will be stored.
*/
          folder: "your_folder_name",
        });
      } catch (e) {
//returns an error message on image upload failure.
        return `Image could not be uploaded:${e.message}`;
      }
/*returns uploaded photo url if successful `result.url`.
if we were going to store image name in database,this
*/
      return `Successful-Photo URL: ${result.url}`;
    },
  },
};
const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: true,
});
/*
Using Apollo Server’s applyMiddleware() method, you can opt-in any middleware, which in this case is Express.
*/
server.applyMiddleware({ app });

//starts listening on our port
app.listen(PORT, () => {
  console.log(
    `🚀 Apollo Server started on http://localhost:${PORT}${server.graphqlPath}`
  );
});

Enter fullscreen mode Exit fullscreen mode

let's start our app

yarn run 
nodemon app.js
Enter fullscreen mode Exit fullscreen mode

let's test our mutation on graphql playground
Access http://localhost:4000/playground from your browser and type :

mutation {
  uploadPhoto(photo:"image_location.jpg")
}
Enter fullscreen mode Exit fullscreen mode

where image_location.jpg is a valid image location whether remote or local

Alt Text

If you have followed every step carefully,your image should be uploaded to Cloudinary.
♨️ Congrats
Here is a link to the full project on my github repository.

Top comments (1)

Collapse
 
leonbuitrago profile image
Leon buitrago

hola que tal me gustaria saber como implemetar la siguiente mutacion en react con una sola variable para varios elementos:

mutation creandopedido($creapedido: PedidoInput!) {
crearPedido(input: $creapedido) {
_id
nombre
direccion
pedido
whatsapp
correo
}
}

PedidoInput!:
nombre: String
direccion: String
pedido: [String]
whatsapp: String
correo: String