All files historyStore.ts

100% Statements 75/75
100% Branches 9/9
100% Functions 7/7
100% Lines 75/75

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 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 761x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 114x 114x 114x 114x 114x 114x 114x 5x 5x 114x 114x 114x 11x 11x 9x 9x 11x 11x 2x 2x 2x 11x 11x 11x 11x 11x 11x 9x 9x 11x 11x 11x 116x 116x 116x 116x 11x  
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
 
export interface HistoryEntry {
  id: string;
  timestamp: number;
  request: {
    method: string;
    url: string;
    headers: Record<string, string>;
    body?: string;
  };
  response?: {
    status: number;
    statusText: string;
    headers: Record<string, string>;
    body: string;
    duration: number;
  };
  error?: string;
  sourceFile?: string;
  requestName?: string;
}
 
export class HistoryStore {
  private entries: HistoryEntry[] = [];
  private readonly maxEntries = 100;
  private readonly storePath: string;
 
  constructor(globalStorageUri: vscode.Uri) {
    const dir = globalStorageUri.fsPath;
    fs.mkdirSync(dir, { recursive: true });
    this.storePath = path.join(dir, 'history.json');
    this.load();
  }
 
  add(entry: Omit<HistoryEntry, 'id' | 'timestamp'>): HistoryEntry {
    const full: HistoryEntry = {
      ...entry,
      id: `${Date.now()}-${Math.random().toString(36).slice(2, 5)}`,
      timestamp: Date.now(),
    };
    this.entries.unshift(full);
    if (this.entries.length > this.maxEntries) {
      this.entries.length = this.maxEntries;
    }
    this.persist();
    return full;
  }
 
  getAll(): HistoryEntry[] {
    return this.entries;
  }
 
  clear(): void {
    this.entries = [];
    this.persist();
  }
 
  private load(): void {
    try {
      const raw = fs.readFileSync(this.storePath, 'utf8');
      this.entries = JSON.parse(raw) as HistoryEntry[];
    } catch {
      this.entries = [];
    }
  }
 
  private persist(): void {
    const tmp = this.storePath + '.tmp';
    fs.writeFileSync(tmp, JSON.stringify(this.entries), 'utf8');
    fs.renameSync(tmp, this.storePath);
  }
}