A lightweight and efficient caching solution built with Node.js and TypeScript using the node-cache package. This project provides an in-memory caching service to improve application performance by storing and reusing frequently accessed data.
This project is designed to demonstrate how to use caching to optimize data retrieval in a Node.js application. The caching layer allows repeated requests for the same data to be handled quickly by leveraging in-memory storage, significantly reducing database or API calls.
- Implements caching using the
node-cachelibrary. - Provides data retrieval via cached data or fresh data.
- Automatically refreshes cache when new data is inserted.
- Supports expiration and TTL (Time-to-Live) for cached data.
To set up the project, follow these steps:
-
Clone the repository:
git clone https://github.com/KhaledSaeed18/nodejs-backend-caching.git cd node-cache -
Install dependencies:
npm install
To start the development server, use:
npm run devThis will start the server and automatically restart on file changes using nodemon.
-
GET /users: Fetches user data with caching.
Request URL:
GET http://localhost:3000/api/users
-
POST /users: Adds a new user to the mock data collection and refreshes the cache.
Request URL:
POST http://localhost:3000/api/users
Request Body:
{ "id": 11, "name": "John Doe", "email": "[email protected]", "age": 30, "role": "developer", "country": "USA" }
/src
/cacheService.ts // Caching logic using node-cache
/mockData.ts // Mock data for demonstration
/routes.ts // API routes for users
/server.ts // Server initialization
/package.json
/tsconfig.jsonThe node-cache package is an in-memory caching solution for Node.js applications. It provides fast and simple caching with features such as:
- Time-to-live (TTL) and expiration handling
- Ability to store different types of data (strings, objects, etc.)
- Automatic cleanup of expired cache entries
- Keys with individual TTL settings
- Event handling for expired keys
set(key, value, [ttl]): Store a value with optional TTLget(key): Retrieve a value by keydel(key): Delete a key from cachehas(key): Check if key existskeys(): Get all existing keysgetStats(): Retrieve cache statisticsflushAll(): Clear entire cacheclose(): Clean up and shutdown the cache
mset(): Set multiple keys at oncemget(): Get multiple keys at oncemdel(): Delete multiple keysgetTtl(): Get remaining TTL for a key
expired: Triggered when a key expiresflush: Triggered when cache is cleareddel: Triggered when a key is deleted
This caching solution is perfect for reducing database load and improving application response times.