Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / JavaScript

IDBObjectStore — un archivio di record IndexedDB

IDBObjectStore espone i record IndexedDB tramite un riferimento associato a una transazione. Consente di aggiungere, sostituire, leggere, eliminare e contare i dati, oltre a usare indici secondari.

Versione: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Sintassi

const store = transaction.objectStore(name);
store.createIndex(name, keyPath, options); // upgrade transaction only
store.add(value, key); // key may be omitted
store.put(value, key); // key may be omitted
store.getAll(query, count); // query and count are optional
store.delete(query);
store.count(query); // query is optional
store.index(name);

IDBObjectStore è un riferimento a un archivio di record IndexedDB, associato a una transazione specifica. Ogni record ha una chiave primaria e un valore copiato tramite structured clone. keyPath: "id" ricava la chiave dal campo id; con questa configurazione, non passare una chiave separata a add() o put().

add() inserisce un record; una chiave duplicata causa un errore ConstraintError. put() inserisce un record oppure sostituisce l’intero valore associato a una chiave esistente: non unisce i campi. delete(query) elimina i record in base alla chiave primaria o a un intervallo di chiavi. Queste operazioni richiedono una transazione che consenta le scritture. getAll(query?, count?) recupera i valori, ordinati per chiave primaria crescente per impostazione predefinita; count(query?) conta i record corrispondenti. Se la query viene omessa, viene considerato l’intero archivio.

createIndex(name, keyPath, options) crea un indice solo durante una transazione di aggiornamento dello schema, di solito in onupgradeneeded; unique: true impone l’unicità delle chiavi dell’indice. index(name) restituisce un IDBIndex esistente per cercare usando una chiave secondaria. Entrambi i metodi restituiscono riferimenti in modo sincrono; gli altri metodi elencati restituiscono IDBRequest, non Promise.

Il successo di una richiesta non significa che la transazione sia stata confermata: attendi complete e gestisci abort. Accoda le operazioni mentre la transazione è attiva; attendere attività asincrone non correlate può renderla inattiva. L’esempio usa le forme API di IndexedDB 2.0, senza la più recente variante di getAll() con un oggetto di opzioni. È una Web API, non parte di ECMAScript; Node 24 non dimostra il supporto nei browser. Controlla che indexedDB sia disponibile nell’ambiente di destinazione.

Identificatori di riferimento trattati in questa voce: IDBObjectStore.createIndex, IDBObjectStore.add, IDBObjectStore.getAll, IDBObjectStore.delete, IDBObjectStore.put, IDBObjectStore.count, IDBObjectStore.index.

Esempi

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>IDBObjectStore: working with records</title>
</head>
<body>
  <h1>Working with an IndexedDB object store</h1>
  <script>
    (() => {
      const name = 'cktis-store-' + crypto.getRandomValues(new Uint32Array(4)).join('-');
      const report = error => console.log(error.name === 'SecurityError'
        ? 'IndexedDB unavailable: SecurityError' : `IndexedDB error: ${error.name}`);
      let factory, opening;
      try {
        factory = window.indexedDB;
        if (!factory) {
          console.log('IndexedDB unavailable: API missing');
          return;
        }
        opening = factory.open(name, 1);
      } catch (error) {
        report(error);
        return;
      }
      let created = false;
      opening.onerror = () => report(opening.error);
      opening.onupgradeneeded = () => {
        created = true;
        const store = opening.result.createObjectStore('items', { keyPath: 'id' });
        store.createIndex('byLabel', 'label', { unique: true });
      };
      opening.onsuccess = () => {
        const db = opening.result;
        if (!created) {
          db.close();
          console.log('Fixture name already in use');
          return;
        }
        const tx = db.transaction('items', 'readwrite');
        const store = tx.objectStore('items');
        store.add({ id: 1, label: 'draft' });
        store.add({ id: 2, label: 'spare' });
        store.put({ id: 1, label: 'final' });
        store.delete(2);
        const all = store.getAll();
        const count = store.count();
        const indexed = store.index('byLabel').get('final');
        const cleanup = () => {
          db.close();
          factory.deleteDatabase(name);
        };
        tx.oncomplete = () => {
          console.log(JSON.stringify({ items: all.result, count: count.result, indexedId: indexed.result.id }));
          cleanup();
        };
        tx.onabort = () => {
          report(tx.error);
          cleanup();
        };
      };
    })();
  </script>
</body>
</html>

Risultato

Successful browser run (IndexedDB access permitted):
{"items":[{"id":1,"label":"final"}],"count":1,"indexedId":1}

If the browser blocks IndexedDB access with a SecurityError, as in the isolated environment:
IndexedDB unavailable: SecurityError

Il codice mostrato e il risultato dichiarato sono stati verificati in un ambiente isolato con il metodo registrato nella prova di verifica di questa versione esatta.

Fonti