Browse Source

Migrate LocalStorage to TS

pull/4830/head
Artur Arseniev 3 years ago
parent
commit
54d0070ade
  1. 15
      src/storage_manager/config/config.ts
  2. 9
      src/storage_manager/model/IStorage.ts
  3. 28
      src/storage_manager/model/LocalStorage.js
  4. 43
      src/storage_manager/model/LocalStorage.ts

15
src/storage_manager/config/config.ts

@ -1,21 +1,8 @@
import Editor from '../../editor';
import { LocalStorageConfig } from '../model/LocalStorage';
type AnyObject = Record<string, any>;
export interface LocalStorageConfig {
/**
* Local key identifier of the project.
* @default 'gjsProject'
*/
key?: string;
/**
* If enabled, checks if browser supports LocalStorage.
* @default true
*/
checkLocal?: boolean;
}
export interface RemoteStorageConfig {
/**
* Custom headers.

9
src/storage_manager/model/IStorage.ts

@ -0,0 +1,9 @@
export interface StorageOptions {}
export interface ProjectData {}
export default interface IStorage<T extends StorageOptions = {}> {
load: (options?: T) => Promise<ProjectData>;
store: (data: ProjectData, options?: T) => Promise<any>;
[key: string]: any;
}

28
src/storage_manager/model/LocalStorage.js

@ -1,28 +0,0 @@
import { hasWin } from '../../utils/mixins';
export default class LocalStorage {
async store(data, opts = {}) {
if (this.hasLocal(opts, true)) {
localStorage.setItem(opts.key, JSON.stringify(data));
}
}
async load(opts = {}) {
let result = {};
if (this.hasLocal(opts, true)) {
result = JSON.parse(localStorage.getItem(opts.key) || '{}');
}
return result;
}
hasLocal(opts = {}, thr) {
if (opts.checkLocal && (!hasWin() || !localStorage)) {
if (thr) throw new Error('localStorage not available');
return false;
}
return true;
}
}

43
src/storage_manager/model/LocalStorage.ts

@ -0,0 +1,43 @@
import { hasWin } from '../../utils/mixins';
import IStorage, { ProjectData } from './IStorage';
export interface LocalStorageConfig {
/**
* Local key identifier of the project.
* @default 'gjsProject'
*/
key?: string;
/**
* If enabled, checks if browser supports LocalStorage.
* @default true
*/
checkLocal?: boolean;
}
export default class LocalStorage implements IStorage<LocalStorageConfig> {
async store(data: ProjectData, opts: LocalStorageConfig = {}) {
if (this.hasLocal(opts, true)) {
localStorage.setItem(opts.key!, JSON.stringify(data));
}
}
async load(opts: LocalStorageConfig = {}) {
let result = {};
if (this.hasLocal(opts, true)) {
result = JSON.parse(localStorage.getItem(opts.key!) || '{}');
}
return result;
}
hasLocal(opts: LocalStorageConfig = {}, thr?: boolean) {
if (opts.checkLocal && (!hasWin() || !localStorage)) {
if (thr) throw new Error('localStorage not available');
return false;
}
return true;
}
}
Loading…
Cancel
Save