storage/src/index.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

import { KeyValueStorage, MemoryStorage, RefScopedStorage, ScopedStorage } from "./basic";
import { BrowserLocalStorage } from "./browser";
2019-11-07 21:33:23 +00:00
import { NodeDirectoryStorage } from "./node";
import { RestRemoteStorage } from "./remote";
/**
2019-11-14 17:21:44 +00:00
* Base type for storage usage
*/
export type TKStorage = KeyValueStorage
2019-11-14 17:21:44 +00:00
/**
* Exposed classes
*/
export { MemoryStorage, ScopedStorage, RefScopedStorage, BrowserLocalStorage, NodeDirectoryStorage, RestRemoteStorage };
2019-11-14 17:21:44 +00:00
/**
* Get the best "local" storage available
*/
export function getLocalStorage(appname: string): TKStorage {
2019-11-07 21:33:23 +00:00
try {
return new ScopedStorage(new BrowserLocalStorage(), appname);
} catch {
try {
return new NodeDirectoryStorage(appname);
} catch {
console.warn("No persistent storage available, using in-memory volatile storage");
return new MemoryStorage();
}
}
}
2019-11-14 17:15:03 +00:00
/**
* Get a remote storage, based on an URI
*
* If *shared* is set to true, a namespace will be used to avoid collisions, using getLocalStorage to persist it
*/
export function getRemoteStorage(appname: string, uri: string, options = { shared: false }): TKStorage {
let storage: TKStorage = new RestRemoteStorage(appname, uri);
storage = new ScopedStorage(storage, appname);
if (options.shared) {
storage = new RefScopedStorage(getLocalStorage(appname), storage);
}
return storage;
}
2019-11-14 17:15:03 +00:00
/**
2019-11-14 17:21:44 +00:00
* Get a in-memory volatile storage
2019-11-14 17:15:03 +00:00
*/
export function getMemoryStorage(): TKStorage {
2019-11-14 17:15:03 +00:00
return new MemoryStorage();
}