Utilities

Cache Service

In-memory caching service with time-based expiration.

Source Code

File: src/utils/services/cache.service.ts

import { Injectable } from '@angular/core';

interface CacheEntry<T = unknown> {
  data: T;
  timestamp: number;
}

const cacheDuration = 60 * 1000 * 60;

@Injectable({ providedIn: 'root' })
export class CacheService {
  private cache = new Map<string, CacheEntry>();

  setCache<T = unknown>(id: string, data: T) {
    const entry: CacheEntry<T> = {
      data,
      timestamp: Date.now(),
    };
    this.cache.set(id, entry);
  }

  getCache<T = unknown>(id: string) {
    const cachedResponse = this.cache.get(id);
    if (cachedResponse && this.isCacheValid(cachedResponse)) {
      return cachedResponse.data as T;
    }
    return;
  }

  private isCacheValid(cacheEntry: CacheEntry): boolean {
    return Date.now() - cacheEntry.timestamp < cacheDuration;
  }
}

Description

The CacheService is an Angular service that provides simple in-memory caching with automatic expiration.

Features

  • Generic Type Support: Methods use TypeScript generics for type-safe cache storage and retrieval
  • Automatic Expiration: Cached entries expire after 60 minutes (3,600,000 milliseconds)
  • Simple API: Two main methods for setting and getting cached data
  • Singleton Service: Provided in root, ensuring single instance across the application

Methods

setCache(id: string, data: T): Stores data in cache with a unique identifier and current timestamp

getCache(id: string): Retrieves cached data if it exists and hasn't expired, returns undefined otherwise

Cache Duration

Default cache duration is set to 60 minutes. Expired entries are automatically ignored during retrieval.

Found a bug? Let us know →

Angular Material Blocks Logo

Angular Material Dev UI (or Angular Material Blocks) is one place stop for developers to explore components and blocks for their Angular Material and Tailwind CSS based applications.

Find us on X (Twitter), LinkedIn, Instagram & Threads