All files / app/service idempotencyService.ts

100% Statements 26/26
100% Branches 8/8
100% Functions 7/7
100% Lines 26/26

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 275x 5x 5x 5x 5x 1x 1x 1x 3x 3x 1x 1x 3x 3x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x  
import { IStorage } from '../types/IStorage.js';
 
const IDEMPOTENCY_TTL_MILLISECONDS = 1000 * 60 * 2; // 2 minutes
 
export class IdempotencyService {
  private readonly storageService;
 
  constructor(storageService: IStorage) {
    this.storageService = storageService;
  }
 
  private getStorageKey(idempotencyKey: string): string {
    return `idempotency_${idempotencyKey}`;
  }
 
  public async getIdempotency<T>(idempotencyKey: string): Promise<T | null> {
    const data = await this.storageService.get(this.getStorageKey(idempotencyKey));
    return data ? (JSON.parse(data) as T) : null;
  }
 
  public async setIdempotency<T>(idempotencyKey: string, data: T): Promise<string> {
    return this.storageService.set(this.getStorageKey(idempotencyKey), JSON.stringify(data), {
      expirationMilliseconds: IDEMPOTENCY_TTL_MILLISECONDS,
    });
  }
}