express-easy-curd
Version:
A lightweight helper library for building Express.js routes, controllers, and Redis-enhanced middleware with optional Redis support.
59 lines (58 loc) • 2.84 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const redisCacheKeyGenerator_1 = __importDefault(require("../helpers/redisCacheKeyGenerator"));
const globalHelper_1 = require("../helpers/globalHelper");
const cacheMiddleware = (redis) => (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
try {
const method = req.method.toUpperCase();
const baseUrl = req.baseUrl.toLowerCase(); // e.g., /api/v1/user
const cachePrefix = `*${baseUrl}*`; // used for deletion
if (method === "GET") {
const cacheKey = (0, redisCacheKeyGenerator_1.default)(req);
const cachedData = yield redis.get(cacheKey);
if (cachedData) {
const parsed = JSON.parse(cachedData);
const isSingle = ((_a = req.params) === null || _a === void 0 ? void 0 : _a.id) !== undefined;
const payload = isSingle
? {
success: true,
message: `Fetched successfully`,
data: parsed,
}
: {
success: true,
message: `Fetched successfully`,
data: parsed === null || parsed === void 0 ? void 0 : parsed.data,
meta: parsed === null || parsed === void 0 ? void 0 : parsed.meta,
};
return (0, globalHelper_1.sendResponse)(res, 200, payload);
}
return next(); // Cache miss → go to controller
}
// For mutations → invalidate all related cache
if (["POST", "PUT", "DELETE", "PATCH"].includes(method)) {
const keys = yield redis.keys(cachePrefix);
if (keys.length > 0) {
yield redis.call("DEL", ...keys);
}
}
return next();
}
catch (error) {
return next(error);
}
});
exports.default = cacheMiddleware;