93 lines
2.7 KiB
TypeScript
93 lines
2.7 KiB
TypeScript
let request: IDBOpenDBRequest;
|
|
let db: IDBDatabase;
|
|
let version = 1;
|
|
|
|
export enum Stores {
|
|
Departure = 'departure',
|
|
Arrival = 'arrival'
|
|
}
|
|
|
|
export const initDB = (): Promise<boolean | IDBDatabase> => {
|
|
return new Promise((resolve) => {
|
|
request = indexedDB.open('myDB');
|
|
|
|
request.onupgradeneeded = (e) => {
|
|
let req = (e.target as IDBOpenDBRequest)
|
|
db = req.result;
|
|
|
|
if (!db.objectStoreNames.contains(Stores.Arrival)) {
|
|
db.createObjectStore(Stores.Arrival, { keyPath: 'id' });
|
|
}
|
|
if (!db.objectStoreNames.contains(Stores.Departure)) {
|
|
db.createObjectStore(Stores.Departure, { keyPath: 'id' });
|
|
}
|
|
};
|
|
|
|
request.onsuccess = (e) => {
|
|
let req = (e.target as IDBOpenDBRequest)
|
|
db = req.result;
|
|
version = db.version;
|
|
resolve(req.result);
|
|
};
|
|
|
|
request.onerror = (e) => {
|
|
resolve(false);
|
|
};
|
|
});
|
|
};
|
|
|
|
export const addData = <T>(storeName: string, data: T): Promise<T | string | null> => {
|
|
return new Promise((resolve) => {
|
|
const tx = db.transaction(storeName, 'readwrite');
|
|
const store = tx.objectStore(storeName);
|
|
store.add(data);
|
|
resolve(data);
|
|
});
|
|
};
|
|
|
|
export const deleteData = (storeName: string, key: number): Promise<boolean> => {
|
|
return new Promise((resolve) => {
|
|
const tx = db.transaction(storeName, 'readwrite');
|
|
const store = tx.objectStore(storeName);
|
|
const res = store.delete(key);
|
|
console.log("removing" + key)
|
|
res.onsuccess = () => {
|
|
console.log("success")
|
|
resolve(true);
|
|
};
|
|
res.onerror = () => {
|
|
console.log("error")
|
|
resolve(false);
|
|
}
|
|
});
|
|
};
|
|
|
|
export const updateData = <T>(storeName: string, key: number, data: T): Promise<T | string | null> => {
|
|
return new Promise((resolve) => {
|
|
const tx = db.transaction(storeName, 'readwrite');
|
|
const store = tx.objectStore(storeName);
|
|
const res = store.get(key);
|
|
res.onsuccess = () => {
|
|
const newData = { ...res.result, ...data };
|
|
store.put(newData);
|
|
resolve(newData);
|
|
};
|
|
res.onerror = () => {
|
|
resolve(null);
|
|
}
|
|
});
|
|
};
|
|
|
|
export const getStoreData = <T>(storeName: Stores): Promise<T[] | null> => {
|
|
return new Promise((resolve) => {
|
|
const tx = db.transaction(storeName, 'readonly');
|
|
const store = tx.objectStore(storeName);
|
|
const res = store.getAll();
|
|
res.onsuccess = () => {
|
|
resolve(res.result);
|
|
};
|
|
});
|
|
};
|
|
|
|
export { };
|