Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

socket-cache

3axap4eHko143MIT0.1.129TypeScript support: included

NodeJS socket caching library

socket, cache, http, https

readme

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