-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache-middleware.js
More file actions
87 lines (74 loc) · 3 KB
/
Copy pathcache-middleware.js
File metadata and controls
87 lines (74 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Simple caching middleware for Node-RED
* To use: install as a node dependency in Node-RED
*/
module.exports = function(RED) {
function CacheNode(config) {
RED.nodes.createNode(this, config);
const node = this;
// Cache config
const cacheName = config.cacheName || 'default_cache';
const ttlSeconds = parseInt(config.ttlSeconds) || 3600; // 1 hour default
// Initialize cache if needed
if (!node.context().global.get(cacheName)) {
node.context().global.set(cacheName, {});
}
// Get cache object
const getCache = () => node.context().global.get(cacheName) || {};
// Save cache object
const saveCache = (cache) => {
node.context().global.set(cacheName, cache);
};
// Cleanup expired entries
const cleanupCache = () => {
const cache = getCache();
const now = Date.now();
const ttlMs = ttlSeconds * 1000;
Object.keys(cache).forEach(key => {
if (now - cache[key].timestamp > ttlMs) {
delete cache[key];
}
});
saveCache(cache);
return cache;
};
node.on('input', function(msg) {
const cache = cleanupCache();
// Extract key - handle various message formats
let cacheKey;
if (typeof msg.payload === 'object' && msg.payload.message) {
cacheKey = msg.payload.message;
} else if (typeof msg.payload === 'string') {
cacheKey = msg.payload;
} else {
cacheKey = JSON.stringify(msg.payload);
}
// Check for cache hit
if (cache[cacheKey]) {
msg.payload = cache[cacheKey].value;
msg.cached = true;
node.status({ fill: "green", shape: "dot", text: "Cache hit" });
node.send([null, msg]); // Send to second output (cache hit)
return;
}
// Handle cache miss
msg._cacheKey = cacheKey; // Store key for later use
node.status({ fill: "yellow", shape: "ring", text: "Cache miss" });
node.send([msg, null]); // Send to first output (cache miss)
});
// Listen for messages to the second input (for storing responses)
node.on('input', function(msg, send, done) {
if (msg.cacheStore && msg._cacheKey) {
const cache = getCache();
cache[msg._cacheKey] = {
value: msg.payload,
timestamp: Date.now()
};
saveCache(cache);
node.status({ fill: "blue", shape: "dot", text: "Cached response" });
}
done();
}, 1); // Second input
}
RED.nodes.registerType("cache", CacheNode);
};