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
- NodeJs must be installed on your machine.
- You must have signed up with Cloudinary.
Project Structure
project
| node_modules/
β .env
β app.js
| package.json
| yarn-error.log
| yarn.lock
Let's Begin
let's initialize our server with yarn
yarn init
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
By now your project structure should look like this:
project
| node_modules/
| package.json
| yarn-error.log
| yarn.lock
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
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}`
);
});
let's start our app
yarn run
nodemon app.js
let's test our mutation on graphql playground
Accesshttp://localhost:4000/playground
from your browser and type :
mutation {
uploadPhoto(photo:"image_location.jpg")
}
where image_location.jpg is a valid image location whether remote or local
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)
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