You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
1.9 KiB
80 lines
1.9 KiB
|
1 year ago
|
import { Injectable } from "@angular/core";
|
||
|
|
|
||
|
|
export interface IFunc<T> {
|
||
|
|
(prev?: T): T;
|
||
|
|
}
|
||
|
|
|
||
|
|
interface Option<T = any> {
|
||
|
|
stroage?: "local" | "session";
|
||
|
|
defaultValue?: T | IFunc<T>;
|
||
|
|
serializer?: (v: T) => string;
|
||
|
|
deserializer?: (v: string) => T;
|
||
|
|
}
|
||
|
|
|
||
|
|
export const isFunction = (value: unknown): value is Function => typeof value === "function";
|
||
|
|
|
||
|
|
@Injectable()
|
||
|
|
export class StorageService {
|
||
|
|
constructor() {}
|
||
|
|
|
||
|
|
private parseOption(option?: Option) {
|
||
|
|
const storage = option?.stroage === "session" ? sessionStorage : localStorage;
|
||
|
|
const serializer = option?.serializer ? option?.serializer : JSON.stringify;
|
||
|
|
const deserializer = option?.deserializer ? option?.deserializer : JSON.parse;
|
||
|
|
let defaultValue = option?.defaultValue;
|
||
|
|
|
||
|
|
if (isFunction(option?.defaultValue)) {
|
||
|
|
defaultValue = option?.defaultValue();
|
||
|
|
}
|
||
|
|
|
||
|
|
return {
|
||
|
|
storage,
|
||
|
|
serializer,
|
||
|
|
deserializer,
|
||
|
|
defaultValue,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
get<T>(key: string, option?: Option<T>) {
|
||
|
|
const { storage, deserializer, defaultValue } = this.parseOption(option);
|
||
|
|
try {
|
||
|
|
const val = storage.getItem(key);
|
||
|
|
if (val) {
|
||
|
|
return deserializer(val);
|
||
|
|
}
|
||
|
|
} catch (error) {
|
||
|
|
console.error(error);
|
||
|
|
}
|
||
|
|
return defaultValue;
|
||
|
|
}
|
||
|
|
|
||
|
|
set<T>(key: string, value: T | IFunc<T>, option?: Option<T>) {
|
||
|
|
const { storage, serializer, defaultValue } = this.parseOption(option);
|
||
|
|
const val = (isFunction(value) ? value() : value) ?? defaultValue;
|
||
|
|
if (typeof val === "undefined") {
|
||
|
|
storage.removeItem(key);
|
||
|
|
} else {
|
||
|
|
try {
|
||
|
|
storage.setItem(key, serializer(val));
|
||
|
|
} catch (error) {
|
||
|
|
console.error(error);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
remove(key: string, option?: Pick<Option, "stroage">) {
|
||
|
|
const { storage } = this.parseOption(option);
|
||
|
|
storage.removeItem(key);
|
||
|
|
}
|
||
|
|
|
||
|
|
clear(option?: Pick<Option, "stroage">) {
|
||
|
|
const { storage } = this.parseOption(option);
|
||
|
|
storage.clear();
|
||
|
|
}
|
||
|
|
|
||
|
|
keys(option?: Pick<Option, "stroage">) {
|
||
|
|
const { storage } = this.parseOption(option);
|
||
|
|
return Object.keys(storage);
|
||
|
|
}
|
||
|
|
}
|