sockscape/client/src/FileCache.ts

78 lines
2.6 KiB
TypeScript
Raw Normal View History

2017-04-17 18:50:18 +00:00
class FileCache {
private static dbHandle: IDBDatabase = null;
2017-04-18 04:59:38 +00:00
public static initCache(success: ()=>void, error: (error: string)=>void): void {
var request = window.indexedDB.open("fileCache", 3);
2017-04-19 12:10:47 +00:00
2017-05-15 18:19:32 +00:00
request.onupgradeneeded = (event: any) => {
2017-04-19 21:05:28 +00:00
var db: IDBDatabase = event.target.result;
2017-05-15 18:19:32 +00:00
2017-05-30 11:58:29 +00:00
if(db.objectStoreNames.contains("files"))
db.deleteObjectStore("files");
if(db.objectStoreNames.contains("metadata"))
db.deleteObjectStore("metadata");
if(db.objectStoreNames.contains("hashes"))
db.deleteObjectStore("hashes");
2017-05-15 18:19:32 +00:00
db.createObjectStore("files", {keyPath: "name", autoIncrement: false});
db.createObjectStore("metadata", {keyPath: "name", autoIncrement: false});
2017-05-15 18:19:32 +00:00
};
request.onerror = (event: any) => {
error("Could not upgrade the client database to the most recent version.");
};
request.onsuccess = (event: any) => {
FileCache.dbHandle = request.result;
2017-05-15 18:19:32 +00:00
success();
};
}
public static getMeta(fileName: string, success: (meta: FileMeta)=>void, error: (error: string)=>void): void {
var query = FileCache.dbHandle.transaction("metadata");
2017-05-15 18:19:32 +00:00
var store = query.objectStore("metadata");
var request = store.get(fileName);
request.onsuccess = () => {
success(request.result);
2017-04-19 12:10:47 +00:00
};
2017-04-21 02:12:55 +00:00
2017-05-15 18:19:32 +00:00
request.onerror = (event: any) => {
error("Could not get metadata for file "+ fileName);
2017-05-15 18:19:32 +00:00
};
}
public static setMeta(meta: FileMeta) {
var query = FileCache.dbHandle.transaction("metadata", "readwrite");
2017-05-15 18:19:32 +00:00
var store = query.objectStore("metadata");
2017-05-16 21:17:07 +00:00
store.put(meta);
2017-05-15 18:19:32 +00:00
}
public static getFile(fileName: string, success: (name: string, data: Uint8Array)=>void, error: (error: string)=>void): void {
var query = FileCache.dbHandle.transaction("files");
2017-05-15 18:19:32 +00:00
var store = query.objectStore("files");
var request = store.get(fileName);
request.onsuccess = () => {
success(request.result.name, request.result.data);
2017-05-15 18:19:32 +00:00
};
request.onerror = (event: any) => {
error("Could not get contents for file "+ fileName);
2017-05-15 18:19:32 +00:00
};
2017-04-17 18:50:18 +00:00
}
2017-04-19 21:05:28 +00:00
public static setFile(fileName: string, data: Uint8Array) {
var query = FileCache.dbHandle.transaction("files", "readwrite");
2017-05-15 18:19:32 +00:00
var store = query.objectStore("files");
store.put({name: fileName, data: data});
2017-05-15 18:19:32 +00:00
}
2017-05-16 21:17:07 +00:00
}
class FileMeta {
name: string;
type: string;
hash: string;
2017-04-17 18:50:18 +00:00
}