How to Integrate Cloudinary With React and GraphQL
In this lesson, we'll pick up from what we've done in the previous lesson by modifying our server code to utilize Cloudinary to host listing images for our TinyHouse application.
Image uploads with Cloudinary#
🙋🏽 To upload an image asset to the cloud with the Cloudinary API, we'll follow the approach highlighted in the Upload method section of the Cloudinary documentation which can be seen - here.
📝 This module's quiz can be found - here.
🗒️ Solutions for this module's quiz can be found - here.
To use the Cloudinary API in our Node server application, we'll need to first install the relevant cloudinary package. We'll head to our terminal and in our server project, install the npm
cloudinary
library as a dependency.
npm i cloudinary
The community has recently prepared a declaration file directly in the npm
cloudinary
package so we won't have to install additional typings.
Cloudinary
#
Just like how we've set up dedicated files for Stripe and Google to prepare functions to interact with their APIs, we'll create a Cloudinary.ts file in our src/lib/api/
folder responsible in having the function needed to interact with the Cloudinary API.
server/
src/
// ...
lib/
api/
Cloudinary.ts
// ...
// ...
In the src/lib/api/index.ts
file, we'll re-export the soon to be created Cloudinary
object.
export * from "./Cloudinary";
In the src/lib/api/Cloudinary.ts
file, we'll import the cloudinary
module and export an object we'll create called Cloudinary
. The exported object will have an asynchronous function labeled upload()
that will expect an image
argument of type string.
import cloudinary from "cloudinary";
export const Cloudinary = {
upload: async (image: string) => {
// ...
}
};
In our hostListing()
resolver function, we'll call the upload()
function available in our constructed Cloudinary
object and pass the listing base64 encoded image as an argument to the function. The upload()
function will then use the Cloudinary API to upload the image as an asset to our Cloudinary account storage. When successfully uploaded, we'll want the upload()
function to return the uploaded image URL.
We can make an upload happen with an upload()
function available in the cloudinary
module. It's a little verbose but it'll appear something like this - cloudinary.v2.uploader.upload()
. This would be an asynchronous function where we'll be interested in the response that is to be returned.
This page is a preview of TinyHouse: A Fullstack React Masterclass with TypeScript and GraphQL - Part Two