indexeddb

Framework: angular

📦 Installation

Install the latest version using npm:

bash
npm install universe-code@latest

1️⃣ Create an Angular IndexedDB Service

Create the following file:

📁 src/app/services/app-idb.service.ts

ts
import { Injectable } from "@angular/core";
import { IdbService as CoreIdbService } from "universe-code/angular";

interface IdbConfig {
  dbName: string;
  version: number;
  storeName: string;
}

const IDB_CONFIG: IdbConfig = {
  dbName: "dynamicDB",
  version: 1,
  storeName: "store",
};

@Injectable({ providedIn: "root" })
export class AppIdbService {
  private client: any;

  constructor() {
    this.client = new CoreIdbService(IDB_CONFIG);

    // 🔥 Force IndexedDB + objectStore creation when service is constructed
    this.client
      .connect()
      .then(() => {
        console.log("IndexedDB connected / created");
      })
      .catch((err: any) => {
        console.error("IndexedDB connect error:", err);
      });
  }

  fetchWithExpiry(key: string, ttl: number, apiFn: () => Promise<any>) {
    return this.client.getWithExpiry(key, ttl, apiFn);
  }

  get(key: string) {
    return this.client.get(key);
  }

  set(data: any) {
    return this.client.put(data);
  }

  remove(key: string) {
    return this.client.remove(key);
  }

  clear() {
    return this.client.clear();
  }
}

2️⃣ Store api data in indexdb with time interval.

Example AppComponent:

ts
import { Component, OnInit } from "@angular/core";
import { AppIdbService } from "./services/app-idb.service";
import { minutesToMs } from "universe-code/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
  constructor(private readonly idb: AppIdbService) {}

  async ngOnInit(): Promise<void> {
    try {
      const data = await this.idb.fetchWithExpiry(
        "usersList",
        minutesToMs(1),
        () => this.http.get("https://example.com/api/user").toPromise()
      );

      console.log("All Users:", data);
    } catch (error) {
      console.error("Failed to load events:", error);
    }
  }
}

📥 Get Data from IndexedDB

ts
const data = await this.idb.get("users");
console.log(data);

✏️ Insert / Update Data

Default store keyPath is id

ts
await this.idb.set({
  id: "users",
  data: {
    name: "Mark",
    country: "USA",
  },
});

🗑️ Delete a Specific Record

ts
await this.idb.remove("users");

🧹 Clear Entire IndexedDB Store

ts
await this.idb.clear();

📚 API Reference (Angular Wrapper)

AppIdbService

MethodSignatureDescription
fetchWithExpiry(key, ttlMs, apiFn)Fetch & cache data with expiry
get(key)Get record by key
set(data)Insert or update record
remove(key)Delete record
clear()Clear store

⚙️ Core: IdbService

Used internally from universe-code/indexdb:

  • connect()
  • get(key)
  • put(data)
  • remove(key)
  • clear()
  • getWithExpiry(key, ttl, apiFn)

Can also be used outside Angular (JS / TS / other frameworks).


✅ Ideal Use Cases

  • API response caching
  • Offline-first Angular apps
  • Performance optimization
  • Local session & config storage
  • Shared data across routes/components

🛡 License

MIT License © universe-code