Skip to content

Commit 86de505

Browse files
author
FalkWolsky
committed
Improve caching mechanism
1 parent 4103d6f commit 86de505

File tree

2 files changed

+8280
-10969
lines changed

2 files changed

+8280
-10969
lines changed

server/node-service/src/routes/apiRouter.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,37 @@ import express from "express";
22
import * as pluginControllers from "../controllers/plugins";
33
import jsControllers from "../controllers/runJavascript";
44
import * as npmControllers from "../controllers/npm";
5+
import querystring from "querystring";
6+
import { ParsedQs } from 'qs';
57

68
const apiRouter = express.Router();
79

810
// In-memory cache object
911
const cache: { [key: string]: any } = {};
1012

13+
// Helper function to flatten Request Query object
14+
function flatQuery(query: ParsedQs) {
15+
let result: {[key: string]: string | number | boolean | string[] | null} = {};
16+
17+
for (let key in query) {
18+
if (typeof query[key] === 'object' && !Array.isArray(query[key])) {
19+
result[key] = JSON.stringify(query[key]);
20+
} else {
21+
result[key] = query[key] as any;
22+
}
23+
}
24+
25+
return result;
26+
}
27+
1128
// Middleware to cache responses for specific routes
1229
function cacheMiddleware(req: express.Request, res: express.Response, next: express.NextFunction) {
13-
const cacheKey = req.originalUrl;
30+
31+
let cacheKey = req.path + "?" + querystring.stringify(flatQuery(req.query));
32+
33+
if (req.method === "POST" && req.is("application/json") && req.body) {
34+
cacheKey += JSON.stringify(req.body);
35+
}
1436

1537
// Check if the response is already cached
1638
if (cache[cacheKey]) {

0 commit comments

Comments
 (0)