CKTIS / JavaScript
IDBIndex — interrogare un indice IndexedDB
IDBIndex espone i record di un object store tramite una chiave secondaria. Confronta il recupero di un array con getAll() con l’iterazione di un cursore tramite openCursor() e distingui le chiavi dell’indice dalle chiavi primarie.
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 index = transaction.objectStore(storeName).index(indexName);
const valuesRequest = index.getAll(query, count);
const cursorRequest = index.openCursor(query, "next");IDBIndex è un riferimento all’indice secondario di un object store IndexedDB, non un costruttore da usare direttamente. Crea l’indice con createIndex() durante upgradeneeded; in seguito, recuperalo con store.index(name) all’interno di una transazione. L’indice viene aggiornato automaticamente insieme all’object store.
IDBIndex.getAll(query, count) restituisce un IDBRequest, non una Promise. Il risultato è un array di valori dell’object store oppure [] se non ci sono corrispondenze. query accetta una chiave dell’indice o un IDBKeyRange; se viene omesso, corrispondono tutte le voci. Il parametro facoltativo count limita il numero di risultati. Se vale 0 o viene omesso, vengono restituite tutte le corrispondenze. L’ordinamento è crescente per chiave dell’indice e poi per chiave primaria.
Anche IDBIndex.openCursor(query, direction) restituisce un IDBRequest. In success, leggi il cursore o null quando non rimangono risultati; continue() avvia il passaggio successivo. cursor.key è la chiave dell’indice, cursor.primaryKey la chiave dell’object store e cursor.value il record. La direzione predefinita è "next"; sono disponibili anche "prev", "nextunique" e "prevunique".
Un cursore consente di elaborare i dati progressivamente; getAll() materializza l’intero array dei risultati. Invia le richieste mentre la transazione è attiva; non inserire tra loro un await non correlato. L’esempio usa la sintassi IndexedDB 2.0, senza la forma più recente delle opzioni di getAll(). Verifica il browser di destinazione: avere Node 24 non dimostra il supporto di questa Web API.
Esempi
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IDBIndex: querying a secondary key</title>
</head>
<body>
<h1>Querying an IndexedDB index</h1>
<script>
(() => {
const name = 'cktis-index-' + 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('tokens', { keyPath: 'id' });
store.createIndex('byColor', 'color');
store.add({ id: 2, color: 'blue', token: 'square' });
store.add({ id: 1, color: 'blue', token: 'circle' });
store.add({ id: 3, color: 'red', token: 'triangle' });
};
opening.onsuccess = () => {
const db = opening.result;
if (!created) {
db.close();
console.log('Fixture name already in use');
return;
}
const tx = db.transaction('tokens', 'readonly');
const index = tx.objectStore('tokens').index('byColor');
const all = index.getAll('blue');
const scan = index.openCursor('blue');
const rows = [];
scan.onsuccess = () => {
const cursor = scan.result;
if (cursor) {
rows.push([cursor.key, cursor.primaryKey, cursor.value.token]);
cursor.continue();
}
};
const cleanup = () => {
db.close();
factory.deleteDatabase(name);
};
tx.oncomplete = () => {
console.log(JSON.stringify(all.result.map(record => record.token)));
console.log(JSON.stringify(rows));
cleanup();
};
tx.onabort = () => {
report(tx.error);
cleanup();
};
};
})();
</script>
</body>
</html>Risultato
When IndexedDB access is allowed and the query succeeds, both lines show matches for the index key "blue" in ascending primary-key order: ["circle","square"] [["blue",1,"circle"],["blue",2,"square"]] If the browser denies IndexedDB access with a SecurityError, the example logs instead: 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.