Connect to Serverless Redis via GraphQL from wherever you send HTTP Requests
In this article, we will take a look at accessing the Redis database directly from your client app.
In this article, we will implement an event booking application, which will include the following features:
- Creating an event in the database.
- Pushing events to the cache.
- Cache trending events, so we will run the CRON job for updating trending events in cache periodically.
- On the client-side React app, we will be fetching trending events directly from the Redis server using GraphQL, ie, no need to connect with the actual server.
REST API Routes
1. POST => /api/events => Create events
2. GET => /api/events => Get all events
Software requirements
- Node.js — Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
- Express — Fast, unopinionated, minimalist web framework for Node.js
- Postman — A collaboration platform for API development.
Let’s begin.
Install the required packages on your local machine:
npm install express mongoose dotenv redis — save
Set up Redis database with Upstash
Upstash is a serverless database for Redis. With servers/instances, you usually pay per hour or at a fixed price. With serverless, you pay-per-request.
This means you’re not charged when the database isn’t in use. Upstash configures and manages the database for you.
Start by creating an account on Upstash.
Now set up the Redis database instance.
Don’t forget to add the .env
file in the root directory.
Create a simple server and connect to the local or remote MongoDB database:
Now connect to the Redis server using the configuration provided by Upstash:
Mongoose model:
Now implement the logic for caching trending events periodically. Basically here, we are using a setInterval()
mock-up CRON job.
Now implement API routes:
For creating the event, we require thetitle, description, imageURL, timeAndDate, fees, notes
from user.
Also, we are pushing these events in the Redis cache.
Final code for server app:
Now, Let’s implement a client app using React
Create boilerplate code for React by running the following command:
npx create-react-app client-app && cd client-app
Install the Apollo client library:
npm i @apollo/client
Now, connect to the Redis database. In your index.js file, add following code to set up the GraphQL client and connect to Upstash’s GraphQL server:
Get credentials from Upstash:
Note: Use
READ ONLY
access key on client-side.
Now add Bootstrap for UI:
Implement code for fetching trending events directly from Upstash Redis:
Then try to run using npm start
:
You will see trending events, directly fetched from the Redis database.
Check out Upstash for production.
More content at plainenglish.io