जावास्क्रिप्ट और इंडेक्सडबी

जावास्क्रिप्ट और इंडेक्सडबी

इस लेख में, हम जावास्क्रिप्ट और इंडेक्सडबी के बारे में समझाएंगे।

यह ट्यूटोरियल जावास्क्रिप्ट और IndexedDB का चरण-दर-चरण विवरण प्रदान करता है, जिसमें प्रत्येक चरण पर व्यावहारिक उदाहरण कोड शामिल हैं, ताकि आपकी समझ और गहरी हो सके।

YouTube Video

javascript-indexed-db.html
  1<!DOCTYPE html>
  2<html lang="en">
  3<head>
  4  <meta charset="UTF-8">
  5  <title>JavaScript &amp; HTML</title>
  6  <style>
  7    * {
  8        box-sizing: border-box;
  9    }
 10
 11    body {
 12        margin: 0;
 13        padding: 1em;
 14        padding-bottom: 10em;
 15        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 16        background-color: #f7f9fc;
 17        color: #333;
 18        line-height: 1.6;
 19    }
 20
 21    .container {
 22        max-width: 800px;
 23        margin: 0 auto;
 24        padding: 1em;
 25        background-color: #ffffff;
 26        border: 1px solid #ccc;
 27        border-radius: 10px;
 28        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 29    }
 30
 31    .container-flex {
 32        display: flex;
 33        flex-wrap: wrap;
 34        gap: 2em;
 35        max-width: 1000px;
 36        margin: 0 auto;
 37        padding: 1em;
 38        background-color: #ffffff;
 39        border: 1px solid #ccc;
 40        border-radius: 10px;
 41        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 42    }
 43
 44    .left-column, .right-column {
 45        flex: 1 1 200px;
 46        min-width: 200px;
 47    }
 48
 49    h1, h2 {
 50        font-size: 1.2rem;
 51        color: #007bff;
 52        margin-top: 0.5em;
 53        margin-bottom: 0.5em;
 54        border-left: 5px solid #007bff;
 55        padding-left: 0.6em;
 56        background-color: #e9f2ff;
 57    }
 58
 59    button {
 60        display: block;
 61        margin: 1em auto;
 62        padding: 0.75em 1.5em;
 63        font-size: 1rem;
 64        background-color: #007bff;
 65        color: white;
 66        border: none;
 67        border-radius: 6px;
 68        cursor: pointer;
 69        transition: background-color 0.3s ease;
 70    }
 71
 72    button:hover {
 73        background-color: #0056b3;
 74    }
 75
 76    #output {
 77        margin-top: 1em;
 78        background-color: #1e1e1e;
 79        color: #0f0;
 80        padding: 1em;
 81        border-radius: 8px;
 82        min-height: 200px;
 83        font-family: Consolas, monospace;
 84        font-size: 0.95rem;
 85        overflow-y: auto;
 86        white-space: pre-wrap;
 87    }
 88
 89    .highlight {
 90        outline: 3px solid #ffc107; /* yellow border */
 91        background-color: #fff8e1;  /* soft yellow background */
 92        transition: background-color 0.3s ease, outline 0.3s ease;
 93    }
 94
 95    .active {
 96        background-color: #28a745; /* green background */
 97        color: #fff;
 98        box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
 99        transition: background-color 0.3s ease, box-shadow 0.3s ease;
100    }
101  </style>
102</head>
103<body>
104    <div class="container">
105        <h1>JavaScript Console</h1>
106        <button id="executeBtn">Execute</button>
107        <div id="output"></div>
108    </div>
109
110    <script>
111        // Override console.log to display messages in the #output element
112        (function () {
113            // Override console.log
114            const originalLog = console.log;
115            console.log = function (...args) {
116                originalLog.apply(console, args);
117                const message = document.createElement('div');
118                message.textContent = args
119                    .map(arg => (typeof arg === "object" && arg !== null ? JSON.stringify(arg) : String(arg)))
120                    .join(" ");
121                output.appendChild(message);
122            };
123
124            // Override console.error
125            const originalError = console.error;
126            console.error = function (...args) {
127                originalError.apply(console, args);
128                const message = document.createElement('div');
129                message.textContent = args
130                    .map(arg => (typeof arg === "object" && arg !== null ? JSON.stringify(arg) : String(arg)))
131                    .join(" ");
132                message.style.color = 'red'; // Color error messages red
133                output.appendChild(message);
134            };
135        })();
136
137        document.getElementById('executeBtn').addEventListener('click', () => {
138            // Prevent multiple loads
139            if (document.getElementById('externalScript')) return;
140
141            const script = document.createElement('script');
142            script.src = 'javascript-indexed-db.js';
143            script.id = 'externalScript';
144            //script.onload = () => console.log('javascript-indexed-db.js loaded and executed.');
145            //script.onerror = () => console.log('Failed to load javascript-indexed-db.js.');
146            document.body.appendChild(script);
147        });
148    </script>
149</body>
150</html>

जावास्क्रिप्ट और इंडेक्सडबी

IndexedDB एक एसिंक्रोनस कुंजी-मूल्य स्टोर डेटाबेस है, जो ब्राउज़रों में निर्मित होता है। यह रिलेशनल डाटाबेस के समान फ़ीचर प्रदान करता है और आपको क्लाइंट-साइड पर बड़ी मात्रा में संरचित डेटा संग्रहीत और खोजने की अनुमति देता है। यह ऑफ़लाइन सक्षम ऐप्लिकेशंस और PWAs (प्रोग्रेसिव वेब ऐप्स) के लिए विशेष रूप से उपयोगी है।

IndexedDB की विशेषताएं

  • एसिंक्रोनस और ईवेंट-ड्रिवन तरीके से काम करता है।
  • जावास्क्रिप्ट ऑब्जेक्ट्स को ऑब्जेक्ट स्टोर्स में संग्रहीत किया जा सकता है।
  • क्वेरी या इंडेक्स द्वारा खोज संभव है।
  • इसमें बड़ी संग्रहण क्षमता होती है (सैकड़ों MB या उससे अधिक), जिससे आप कुकीज़ या लोकल स्टोरेज की तुलना में अधिक डेटा स्टोर कर सकते हैं।

डेटाबेस खोलना और बनाना

IndexedDB का उपयोग करने के लिए सबसे पहले आपको एक डेटाबेस खोलना होगा। अगर वह मौजूद नहीं है, तो यह अपने आप बन जाता है।

1const request = indexedDB.open('MyDatabase', 1); // Specify DB name and version
  • open मेथड डेटाबेस असिंक्रोनस तरीके से खोलता है और निम्नलिखित तीन ईवेंट को ट्रिगर करता है।

onsuccess

1// Fired when database is successfully opened
2request.onsuccess = (event) => {
3    const db = event.target.result; // Database instance
4    console.log('Database opened successfully:', db.name);
5};
  • onsuccess ईवेंट तब ट्रिगर होता है जब डेटाबेस सफलतापूर्वक खुलता है। आगे की सभी क्रियाओं को request.result के माध्यम से किए जाना चाहिए, जो इस बिंदु पर उपलब्ध हो जाता है।

onerror

1// Fired when database fails to open
2request.onerror = (event) => {
3    console.error('Failed to open database:', event.target.error);
4};
  • onerror ईवेंट तब ट्रिगर होता है जब डेटाबेस खोलने में विफल रहता है। यहाँ पर त्रुटि लॉगिंग और त्रुटि प्रबंधन किया जाना चाहिए।

onupgradeneeded

 1// Fired when database is newly created or upgraded
 2request.onupgradeneeded = (event) => {
 3    const db = event.target.result;
 4    console.log('Database upgrade needed (or newly created):', db.name);
 5
 6    // Example: Create an object store (like a table) if it doesn’t exist
 7    if (!db.objectStoreNames.contains('users')) {
 8        db.createObjectStore('users', { keyPath: 'id' });
 9        console.log('Object store "users" created');
10    }
11};
  • onupgradeneeded तब ट्रिगर होता है जब डेटाबेस नया बनाया जाता है या जब निर्धारित संस्करण वर्तमान संस्करण से अधिक होता है। टेबल (ऑब्जेक्ट स्टोर्स) बनाना और स्कीमा परिभाषित करना इसी समय किया जाना चाहिए।

ऑब्जेक्ट स्टोर बनाना

सबसे पहले, onupgradeneeded के भीतर एक 'ऑब्जेक्ट स्टोर' (टेबल के समकक्ष) बनाएं।

1request.onupgradeneeded = function (event) {
2    const db = event.target.result;
3    console.log("onupgradeneeded triggered. Database version:", db.version);
4    if (!db.objectStoreNames.contains('users')) {
5        console.log("Creating object store: users");
6        const store = db.createObjectStore('users', { keyPath: 'id' });
7        store.createIndex('name', 'name', { unique: false });
8    }
9};

यहाँ, निम्नलिखित सेटिंग्स लागू होती हैं:।

  • createObjectStore createObjectStore डेटाबेस में नया ऑब्जेक्ट स्टोर बनाने की एक विधि है। आप एक ऑब्जेक्ट स्टोर में रिकॉर्ड स्टोर कर सकते हैं और keyPath तथा अन्य विकल्पों को निर्दिष्ट करके डेटा प्रबंधन का तरीका निर्धारित कर सकते हैं। यह प्रक्रिया onupgradeneeded ईवेंट के अंदर ही करनी चाहिए।

  • keyPath: 'id' keyPath को id प्रॉपर्टी पर सेट करें, जो प्रत्येक रिकॉर्ड को प्राथमिक कुंजी के रूप में अद्वितीय रूप से पहचानता है। इससे डेटा जोड़ते, खोजते या अपडेट करते समय id का स्वचालित उपयोग संभव होता है।

  • createIndex खोज के लिए name प्रॉपर्टी के आधार पर इंडेक्स बनाने के लिए createIndex विधि का उपयोग करें। unique: false सेट करने पर एक ही नाम वाले कई रिकॉर्ड की अनुमति मिलती है।

सफल डेटाबेस कनेक्शन संभालना

सफल डेटाबेस कनेक्शन के बाद निष्पादित होने वाली प्रक्रिया को onsuccess ईवेंट में असाइन करें। इस प्रक्रिया के भीतर, आप डेटाबेस इंस्टेंस प्राप्त करते हैं और डेटा पढ़ने और लिखने की तैयारी करते हैं।

1request.onsuccess = function (event) {
2    const db = event.target.result;
3    console.log('Database opened successfully');
4    // Use db for reading and writing in subsequent operations
5};
  • यह प्रक्रिया तब चलती है जब IndexedDB डेटाबेस कनेक्शन सफलतापूर्वक पूरा होता है।

  • event.target.result में खुला हुआ डेटाबेस इंस्टेंस (IDBDatabase ऑब्जेक्ट) होता है, जिसका उपयोग लेनदेन शुरू करने और ऑब्जेक्ट स्टोर्स को एक्सेस करने के लिए किया जाता है।

  • डेटा जोड़ने, प्राप्त करने, अपडेट करने और डिलीट करने जैसी वास्तविक पढ़ने और लिखने की क्रियाएं db ऑब्जेक्ट द्वारा की जाती हैं।

इस बिंदु पर डेटाबेस तैयार है, इसलिए आप आराम से लेनदेन शुरू कर सकते हैं।

डेटा जोड़ना

यहाँ बताया गया है कि IndexedDB में नया डेटा कैसे जोड़ा जाए।

 1function addUser(db, user) {
 2    const transaction = db.transaction('users', 'readwrite');
 3    const store = transaction.objectStore('users');
 4    const request = store.add(user);
 5
 6    request.onsuccess = () => {
 7        console.log('User added:', user);
 8    };
 9
10    request.onerror = () => {
11        console.error('Add failed:', request.error);
12    };
13}
14
15// Example: Add a user
16request.onsuccess = function (event) {
17    const db = event.target.result;
18    addUser(db, { id: 1, name: 'Alice' });
19    addUser(db, { id: 2, name: 'Bob' });
20    addUser(db, { id: 3, name: 'John' });
21};
  • db.transaction() से एक ट्रांजेक्शन बनाएँ और जिस ऑब्जेक्ट स्टोर पर काम करना है तथा मोड (इस मामले में, readwrite) को निर्धारित करें।
  • store.add() मेथड का उपयोग करके नया डेटा जोड़ें।
  • लेनदेन अपने आप प्रतिबद्ध हो जाते हैं, लेकिन यदि आप कई क्रियाओं को जोड़ना चाहते हैं, तो आप ट्रांजेक्शन एंड ईवेंट के द्वारा उन्हें प्रबंधित कर सकते हैं।

डेटा प्राप्त करना (प्राइमरी की खोज)

यहाँ बताया गया है कि प्राइमरी की का उपयोग करके विशेष डेटा कैसे प्राप्त करें।

 1function getUserById(db, id) {
 2    const transaction = db.transaction('users', 'readonly');
 3    const store = transaction.objectStore('users');
 4    const request = store.get(id);
 5
 6    request.onsuccess = () => {
 7        if (request.result) {
 8            console.log('User found:', request.result);
 9        } else {
10            console.log('User not found');
11        }
12    };
13
14    request.onerror = () => {
15        console.error('Error retrieving user:', request.error);
16    };
17}
18
19// Example: Get a user by id
20request.onsuccess = function (event) {
21    const db = event.target.result;
22    getUserById(db, 1);
23};
  • db.transaction() द्वारा एक केवल-पढ़ने योग्य ट्रांजेक्शन बनाएँ।
  • निर्दिष्ट प्राइमरी की के अनुसार डेटा प्राप्त करने के लिए store.get(id) का उपयोग करें।
  • जब डेटा सफलतापूर्वक प्राप्त होता है तो onsuccess कॉल होता है, और परिणाम उपलब्ध होने पर प्रदर्शित किया जाता है। अगर कोई परिणाम नहीं है, तो इसे 'कोई संबंधित डेटा नहीं' के रूप में माना जाता है।

इंडेक्स सर्च का उपयोग करना

यदि आप प्राइमरी की के अलावा अन्य प्रॉपर्टीज द्वारा खोज करना चाहते हैं, तो पहले से बनाए गए इंडेक्स का उपयोग करें।

 1function getUserByName(db, name) {
 2    const transaction = db.transaction('users', 'readonly');
 3    const store = transaction.objectStore('users');
 4    const index = store.index('name');
 5    const request = index.get(name);
 6
 7    request.onsuccess = () => {
 8        if (request.result) {
 9            console.log('User by name:', request.result);
10        } else {
11            console.log('No user found with that name');
12        }
13    };
14
15    request.onerror = () => {
16        console.error('Error retrieving user by name:', request.error);
17    };
18}
19
20// Example: Get a user by id
21request.onsuccess = function (event) {
22    const db = event.target.result;
23    getUserByName(db, 'Alice');
24};
  • store.index('name') द्वारा पहले से बनाए गए name इंडेक्स को एक्सेस करें।
  • index.get(value) मिलती-जुलती वैल्यू वाला पहला रिकॉर्ड प्राप्त करता है। यदि एक ही वैल्यू के कई रिकॉर्ड हैं, तो आप index.getAll(value) द्वारा उन्हें सभी प्राप्त कर सकते हैं।

डेटा अपडेट करना

मौजूदा डेटा को अपडेट (ओवरराइट) करने के लिए put() मेथड का उपयोग करें।

अगर मिलती-जुलती प्राइमरी की वाला रिकॉर्ड मौजूद है, तो वह अपडेट हो जाता है; अगर नहीं है, तो नया रिकॉर्ड जोड़ा जाता है।

 1function updateUser(db, updatedUser) {
 2    const transaction = db.transaction('users', 'readwrite');
 3    const store = transaction.objectStore('users');
 4    const request = store.put(updatedUser);
 5
 6    request.onsuccess = () => {
 7        console.log('User updated:', updatedUser);
 8    };
 9
10    request.onerror = () => {
11        console.error('Update failed:', request.error);
12    };
13}
14
15// Example: Update user
16request.onsuccess = async (event) => {
17    const db = event.target.result;
18
19    // Test : update existing user
20    updateUser(db, { id: 3, name: 'John Updated' });
21
22    // Test : insert new user
23    updateUser(db, { id: 4, name: 'Charlie' });
24};
  • put() एक सुविधाजनक मेथड है जो अपडेट और जोड़ने दोनों का समर्थन करती है।
  • अगर एक ही प्राइमरी की वाला डेटा पहले से उपलब्ध है, तो उसे ओवरराइट कर दिया जाएगा।
  • अगर आप अपडेट करने से पहले अस्तित्व जांचना चाहते हैं, तो get() का उपयोग पहले से पुष्टि करने के लिए कर सकते हैं।

डेटा मिटाना

निर्दिष्ट प्राइमरी की के संबंधित डेटा को मिटाने के लिए delete() मेथड का उपयोग करें।

 1function deleteUser(db, id) {
 2    const transaction = db.transaction('users', 'readwrite');
 3    const store = transaction.objectStore('users');
 4    const request = store.delete(id);
 5
 6    request.onsuccess = () => {
 7        console.log(`User with id=${id} deleted successfully`);
 8    };
 9
10    request.onerror = () => {
11        console.error(`Failed to delete user with id=${id}:`, request.error);
12    };
13}
14
15// Example: Delete a user by id
16request.onsuccess = function (event) {
17    const db = event.target.result;
18    deleteUser(db, 4);
19};
  • मिलती-जुलती प्राइमरी की वाले डेटा को डिलीट करने के लिए store.delete(id) का उपयोग करें।
  • ध्यान दें, अगर डेटा मौजूद नहीं भी है, तो भी कोई त्रुटि नहीं होगी और इसे सफल माना जाएगा।
  • त्रुटि प्रबंधन लागू करने से अधिक मजबूत कोड मिलेगा।

सभी डेटा प्राप्त करना

getAll()

ऑब्जेक्ट स्टोर में सभी रिकॉर्ड प्राप्त करने के लिए getAll() मेथड का उपयोग करें।

 1function getAllUsers(db) {
 2    const transaction = db.transaction('users', 'readonly');
 3    const store = transaction.objectStore('users');
 4    const request = store.getAll();
 5
 6    request.onsuccess = () => {
 7        console.log('All users:', request.result);
 8    };
 9
10    request.onerror = () => {
11        console.error('Failed to retrieve users:', request.error);
12    };
13}
14
15// Example: Get all users
16request.onsuccess = function (event) {
17    const db = event.target.result;
18    getAllUsers(db);
19};
  • getAll() निर्दिष्ट ऑब्जेक्ट स्टोर में सभी रिकॉर्ड को एक एरे के रूप में प्राप्त करता है।
  • यहाँ तक कि एक बार में बड़ी मात्रा में डेटा प्राप्त करते समय भी यह कुशलता से प्रोसेस होता है।
  • परिणामों को request.result में एरे के रूप में संग्रहित किया जाता है।
  • हमेशा त्रुटि प्रबंधन जोड़ें ताकि आप असफलताओं को संभाल सकें।

openCursor()

openCursor() एक विधि है जो ऑब्जेक्ट स्टोर या इंडेक्स में रिकॉर्ड को क्रमानुसार ब्राउज़ करती है। यह उपयोगी है जब आप एक बार में सभी डेटा प्राप्त करने की बजाय, एक-एक करके डेटा प्रोसेस करना चाहते हैं।

 1function getAllUsersWithCursor(db) {
 2    const transaction = db.transaction('users', 'readonly');
 3    const store = transaction.objectStore('users');
 4    const request = store.openCursor();
 5
 6    request.onsuccess = () => {
 7        const cursor = request.result;
 8        if (cursor) {
 9            console.log('User:', cursor.value); // Process the current record
10            cursor.continue(); // Move to the next record
11        } else {
12            console.log('All users have been processed.');
13        }
14    };
15
16    request.onerror = () => {
17        console.error('Failed to open cursor:', request.error);
18    };
19}
20
21// Example: Get all users
22request.onsuccess = function (event) {
23    const db = event.target.result;
24    getAllUsersWithCursor(db);
25};
  • openCursor() का उपयोग करके आप एक करसर शुरू करते हैं और ऑब्जेक्ट स्टोर में सभी रिकॉर्ड एक-एक करके प्राप्त करते हैं।
  • वर्तमान रिकॉर्ड के डेटा ऑब्जेक्ट को प्राप्त करने के लिए cursor.value का उपयोग करें।
  • करसर को अगले रिकॉर्ड पर ले जाने के लिए cursor.continue() का उपयोग करें।
  • जब cursor === null होता है, तब सभी रिकॉर्ड ब्राउज़ किए जा चुके होते हैं।

openCursor() का उपयोग करके अद्यतन प्रक्रिया का उदाहरण

उदाहरण के लिए, किसी उपयोगकर्ता का नाम जिसका name Alice है, उसे बदलकर Alicia करने की प्रक्रिया कुछ इस प्रकार होगी:।

 1function updateUserName(db, oldName, newName) {
 2    const transaction = db.transaction('users', 'readwrite');
 3    const store = transaction.objectStore('users');
 4    const index = store.index('name'); // Use the 'name' index
 5    const request = index.openCursor(IDBKeyRange.only(oldName));
 6
 7    request.onsuccess = () => {
 8        const cursor = request.result;
 9        if (cursor) {
10            const user = cursor.value;
11            user.name = newName; // Update the name
12            const updateRequest = cursor.update(user);
13
14            updateRequest.onsuccess = () => {
15                console.log('Updated user:', user);
16            };
17
18            updateRequest.onerror = () => {
19                console.error('Failed to update user:', updateRequest.error);
20            };
21
22            cursor.continue();
23        } else {
24            console.log('All matching users have been updated.');
25        }
26    };
27
28    request.onerror = () => {
29        console.error('Cursor error:', request.error);
30    };
31}
32
33// Example: Update user name
34request.onsuccess = function (event) {
35    const db = event.target.result;
36    updateUserName(db, 'Alice', 'Alicia');
37};
  • IDBKeyRange.only(oldName) IDBKeyRange.only का उपयोग करके, आप केवल उन रिकॉर्ड्स को लक्षित कर सकते हैं जिनकी कुंजी ठीक oldName से मेल खाती है। यह तब उपयोगी है जब आप किसी विशेष मान को सीधे एक्सेस करना चाहते हैं।

  • cursor.update() cursor.value को अपडेट करने के बाद, update() कॉल करने पर संबंधित रिकॉर्ड ओवरराइट हो जाएगा।

  • एक से अधिक मेल के प्रबंधन cursor.continue() कॉल कर के, आप कर्सर को अगले मिलते-जुलते रिकॉर्ड पर ले जा सकते हैं। यह आपको क्रम में एक ही कुंजी या शर्त से मेल खाते कई रिकॉर्ड्स को प्रोसेस करने की अनुमति देता है।

  • त्रुटि प्रबंधन किसी प्रक्रिया के विफल होने पर onerror में लॉग आउटपुट करके, कारणों की जांच करना और संचालन के दौरान समस्या हल करना आसान हो जाता है।

openCursor() का उपयोग करके विलोपन प्रक्रिया का उदाहरण

उदाहरण के लिए, उन सभी उपयोगकर्ताओं को हटाने की प्रक्रिया जिनका name Bob है, कुछ इस प्रकार होगी:।

 1function deleteUsersByName(db, targetName) {
 2    const transaction = db.transaction('users', 'readwrite');
 3    const store = transaction.objectStore('users');
 4    const index = store.index('name');
 5    const request = index.openCursor(IDBKeyRange.only(targetName));
 6
 7    request.onsuccess = () => {
 8        const cursor = request.result;
 9        if (cursor) {
10            const deleteRequest = cursor.delete();
11
12            deleteRequest.onsuccess = () => {
13                console.log('Deleted user:', cursor.value);
14            };
15
16            deleteRequest.onerror = () => {
17                console.error('Failed to delete user:', deleteRequest.error);
18            };
19
20            cursor.continue();
21        } else {
22            console.log('All matching users have been deleted.');
23        }
24    };
25
26    request.onerror = () => {
27        console.error('Cursor error:', request.error);
28    };
29}
30
31// Example: Delete user by name
32request.onsuccess = function (event) {
33    const db = event.target.result;
34    deleteUsersByName(db, 'Bob');
35};
  • cursor.delete() cursor.delete() के साथ, वर्तमान कर्सर स्थिति पर मौजूद रिकॉर्ड हटा दिया जाता है। चूंकि परिणाम असिंक्रोनस रूप से लौटता है, आप प्रक्रिया को onsuccess में जांच सकते हैं।

लेन-देन और असिंक्रोनस प्रोसेसिंग पर नोट्स

IndexedDB असिंक्रोनस और इवेंट-ड्रिवन होता है। सभी ऑपरेशन्स को onsuccess या onerror इवेंट्स के साथ हैंडल करना आवश्यक है। जब आप कई प्रक्रियाओं को एक साथ समूहित करना चाहते हैं, तो उन्हें Promise में लपेटना सुविधाजनक होता है।

 1function openDatabase() {
 2    return new Promise((resolve, reject) => {
 3        const request = indexedDB.open('MyDatabase', 1);
 4
 5        request.onupgradeneeded = function (event) {
 6            const db = event.target.result;
 7
 8            // Initialization process (creating object stores and indexes, etc.)
 9            const store = db.createObjectStore('users', { keyPath: 'id' });
10            store.createIndex('name', 'name', { unique: false });
11        };
12
13        request.onsuccess = function (event) {
14            const db = event.target.result;
15            resolve(db);
16        };
17
18        request.onerror = function () {
19            reject(request.error);
20        };
21    });
22}
23
24function addUserAsync(db, user) {
25    return new Promise((resolve, reject) => {
26        const transaction = db.transaction('users', 'readwrite');
27        const store = transaction.objectStore('users');
28        const request = store.add(user);
29
30        request.onsuccess = () => resolve();
31        request.onerror = () => reject(request.error);
32    });
33}
34
35async function main() {
36    try {
37        const db = await openDatabase();
38        await addUserAsync(db, { id: 1, name: 'Alice' });
39        console.log('User added successfully');
40    } catch (error) {
41        console.error('Error:', error);
42    }
43}
  • openDatabase या addUserAsync जैसी फ़ंक्शन्स को Promise के साथ लपेटने से, आप असिंक्रोनस प्रक्रियाओं को सहज रूप से async/await के साथ संभाल सकते हैं।
  • इससे कॉलबैक हेल से बचा जा सकता है और कोड अधिक पठनीय बनता है।

सारांश

ब्राउज़र साइड पर एडवांस्ड डेटा प्रबंधन करना हो तो IndexedDB एक बहुत शक्तिशाली फीचर है। शुरुआत में, ईवेंट-आधारित असिंक्रोनस प्रोसेसिंग से आप भ्रमित हो सकते हैं, लेकिन एक बार संरचना समझ लेने के बाद, आप क्लाइंट साइड पर पूर्ण पैमाने पर डेटा ऑपरेशन कर सकते हैं।

विशेष रूप से, निम्नलिखित बातों का ध्यान रखने से आप इसे अधिक सहजता से उपयोग कर सकेंगे:।

  • onupgradeneeded के साथ प्रारंभिक सेटअप करें।
  • लेन-देन के रीड/राइट मोड पर ध्यान दें।
  • इंडेक्स कुशल खोज की अनुमति देते हैं।
  • डेटा को ऑब्जेक्ट्स के रूप में स्टोर किया जा सकता है, जिससे यह JSON के साथ बहुत अनुकूल होता है।

IndexedDB को भली-भांति सीखने से PWAs और ऑफलाइन ऐप्स के लिए डेटा प्रबंधन बहुत आसान हो जाता है।

आप हमारे YouTube चैनल पर Visual Studio Code का उपयोग करके ऊपर दिए गए लेख के साथ आगे बढ़ सकते हैं। कृपया YouTube चैनल को भी देखें।

YouTube Video