All files / src/sso/schm ServerContextHandleManager.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 10/10
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                    1x   1x 12x     1x 4x     6x 6x       6x 6x       6x 6x 6x 3x 3x   3x               18x 9x        
import { IncomingMessage } from 'http';
import { CtxtHandle } from '../../../lib/api';
 
interface Item {
  id: string;
  timestamp: number;
  handle: CtxtHandle;
}
 
// 2 minutes
const DELAY = 1000 * 60 * 2;
 
const getId = (req: IncomingMessage): string => {
  return req.socket.remoteAddress + '_' + req.socket.remotePort;
};
 
export class ServerContextHandleManager {
  cache: Item[] = [];
 
  release(req: IncomingMessage) {
    this.refresh();
    this.cache = this.cache.filter((v) => v.id !== getId(req));
  }
 
  get(req: IncomingMessage) {
    this.refresh();
    return this.cache.find((v) => v.id === getId(req))?.handle;
  }
 
  set(req: IncomingMessage, handle: CtxtHandle) {
    this.refresh();
    const item = this.cache.find((v) => v.id === getId(req));
    if (item) {
      item.handle = handle;
      return;
    }
    this.cache.push({
      id: getId(req),
      handle,
      timestamp: new Date().getTime(),
    });
  }
 
  refresh() {
    this.cache = this.cache.filter(
      (v) => v.timestamp > new Date().getTime() - DELAY
    );
  }
}