zhongrj
2025-03-28 4ff3eee77b41466d08117970970d01be6e48ffe1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { openDB } from 'idb';
const DB_NAME = 'route-db';
const DB_VERSION = 1;
const STORE_NAME = 'data-store';
 
const dbPromise = openDB(DB_NAME, DB_VERSION, {
    upgrade(db) {
        if (!db.objectStoreNames.contains(STORE_NAME)) {
            db.createObjectStore(STORE_NAME, { keyPath: 'id' });
        }
    },
});
 
export default {
    async addData(data) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        const id = await store.add(data);
        await tx.done;
        return id;
    },
 
    async getAllData() {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readonly');
        const store = tx.objectStore(STORE_NAME);
        return store.getAll();
    },
 
    async getDataById(id) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readonly');
        const store = tx.objectStore(STORE_NAME);
        return store.get(id);
    },
 
    async updateData(id, newData) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        await store.put({ ...newData, id });
        await tx.done;
    },
 
    async deleteData(id) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        await store.delete(id);
        await tx.done;
    },
};