socket-cache
v0.1.129
Published
NodeJS socket caching library
Downloads
50
Readme
Socket Cache
Blazing fast HTTP network socket caching library for NodeJS
Usage
Create inmemory cache
// cache.js
import { cache } from 'socket-cache';
interface CacheKey {
id: string | undefined;
expiresIn: number;
}
interface CacheValue {
value: Buffer[];
expiresAt: number;
}
const storage = new Map<string, CacheValue>();
export default createCache<CacheKey>({
mapToKey: ({ url }) => ({ id: url, expiresIn: 1000 }),
set(key, value) {
if (key.id) {
const expiresAt = Date.now() + key.expiresIn;
storage.set(key.id, { value, expiresAt });
}
},
get(key) {
if (key.id && storage.has(key.id)) {
const { value, expiresAt } = storage.get(key.id);
if (expiresAt > Date.now()) {
return value;
}
storage.delete(key.id);
}
return null;
}
});
Cached server
import http from 'http';
import cache from './cache';
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
const isCached = await cache(req, res);
if (!isCached) {
next();
} else {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`Hello World ${new Date()}`);
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
License
License The MIT License Copyright (c) 2023 Ivan Zakharchanka