12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- class StorageAdapter {
- static session = new StorageAdapter("session");
- static local = new StorageAdapter("local");
- private storage: Storage;
- constructor(type: "session" | "local") {
- if (type === "session") {
- this.storage = window.sessionStorage;
- } else if (type === "local") {
- this.storage = window.localStorage;
- }
- }
- setItem(key: string, value: string | number | Record<string, any>) {
- return this.storage.setItem(key, JSON.stringify(value));
- }
- getItem(key: string) {
- const item = this.storage.getItem(key);
- if (item) {
- try {
- return JSON.parse(item);
- } catch (error) {
- return item;
- }
- }
- return null;
- }
- removeItem(key: string) {
- return this.storage.removeItem(key);
- }
- getStorage() {
- return this.storage;
- }
- get length() {
- return this.storage.length;
- }
- clear() {
- return this.storage.clear();
- }
- key(index: number) {
- return this.storage.key(index);
- }
- }
- export { StorageAdapter };
|