socket-cache
TypeScript icon, indicating that this package has built-in type declarations

0.1.129 • Public • Published

Socket Cache

Blazing fast HTTP network socket caching library for NodeJS

Coverage Status Github Build Status NPM version Downloads Snyk

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

Readme

Keywords

Package Sidebar

Install

npm i socket-cache

Weekly Downloads

17

Version

0.1.129

License

MIT

Unpacked Size

20.3 kB

Total Files

19

Last publish

Collaborators

  • 3axap4ehko