@alwatr/local-storage 9.23.3 → 9.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/dist/facade.d.ts +1 -1
- package/dist/facade.d.ts.map +1 -1
- package/dist/local-storage.provider.d.ts +12 -4
- package/dist/local-storage.provider.d.ts.map +1 -1
- package/dist/main.js +3 -3
- package/dist/main.js.map +4 -4
- package/dist/type.d.ts +13 -1
- package/dist/type.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/facade.ts +1 -1
- package/src/local-storage.provider.ts +11 -6
- package/src/type.ts +15 -1
package/README.md
CHANGED
|
@@ -114,6 +114,19 @@ To completely remove the item from `localStorage`, use the `.remove()` method.
|
|
|
114
114
|
userSettingsProvider.remove();
|
|
115
115
|
```
|
|
116
116
|
|
|
117
|
+
### 6\. Storing Complex Types (Maps, Sets, Dates)
|
|
118
|
+
|
|
119
|
+
By default, the provider uses `JSON.parse` and `JSON.stringify`. If you need to store types that aren't natively supported by JSON (like `Map`, `Set`, or `Date`), you can provide custom `parse` and `stringify` functions in the configuration.
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
const mapProvider = createLocalStorageProvider<Map<string, number>>({
|
|
123
|
+
name: 'score-map',
|
|
124
|
+
schemaVersion: 1,
|
|
125
|
+
stringify: (map) => JSON.stringify(Array.from(map.entries())),
|
|
126
|
+
parse: (str) => new Map(JSON.parse(str)),
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
117
130
|
## Best Practices
|
|
118
131
|
|
|
119
132
|
- **Always use the `createLocalStorageProvider` factory function.** It provides a stable API that protects your code from internal library changes.
|
|
@@ -278,6 +291,19 @@ if (LocalStorageProvider.has(formMeta)) {
|
|
|
278
291
|
userSettingsProvider.remove();
|
|
279
292
|
```
|
|
280
293
|
|
|
294
|
+
### ۶. ذخیرهسازی انواع دادههای پیچیده (Map, Set, Date)
|
|
295
|
+
|
|
296
|
+
به طور پیشفرض، Provider از `JSON.parse` و `JSON.stringify` استفاده میکند. اگر نیاز به ذخیره نوعهایی دارید که به صورت ذاتی توسط JSON پشتیبانی نمیشوند (مانند `Map`، `Set` یا `Date`)، میتوانید توابع سفارشی `parse` و `stringify` را در پیکربندی ارائه دهید.
|
|
297
|
+
|
|
298
|
+
```typescript
|
|
299
|
+
const mapProvider = createLocalStorageProvider<Map<string, number>>({
|
|
300
|
+
name: 'score-map',
|
|
301
|
+
schemaVersion: 1,
|
|
302
|
+
stringify: (map) => JSON.stringify(Array.from(map.entries())),
|
|
303
|
+
parse: (str) => new Map(JSON.parse(str)),
|
|
304
|
+
});
|
|
305
|
+
```
|
|
306
|
+
|
|
281
307
|
## بهترین روشها (Best Practices)
|
|
282
308
|
|
|
283
309
|
- **همیشه از تابع سازنده `createLocalStorageProvider` استفاده کنید.** این تابع یک API پایدار فراهم میکند که کد شما را در برابر تغییرات داخلی کتابخانه محافظت میکند.
|
package/dist/facade.d.ts
CHANGED
|
@@ -21,5 +21,5 @@ import type { LocalStorageProviderConfig } from './type.js';
|
|
|
21
21
|
* console.log(currentSettings); // { theme: 'dark', notifications: false }
|
|
22
22
|
* ```
|
|
23
23
|
*/
|
|
24
|
-
export declare function createLocalStorageProvider<T>(config: LocalStorageProviderConfig): LocalStorageProvider<T>;
|
|
24
|
+
export declare function createLocalStorageProvider<T>(config: LocalStorageProviderConfig<T>): LocalStorageProvider<T>;
|
|
25
25
|
//# sourceMappingURL=facade.d.ts.map
|
package/dist/facade.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"facade.d.ts","sourceRoot":"","sources":["../src/facade.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,oBAAoB,EAAC,MAAM,6BAA6B,CAAC;AAEjE,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,WAAW,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,EAAE,MAAM,EAAE,0BAA0B,GAAG,oBAAoB,CAAC,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"facade.d.ts","sourceRoot":"","sources":["../src/facade.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,oBAAoB,EAAC,MAAM,6BAA6B,CAAC;AAEjE,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,WAAW,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,EAAE,MAAM,EAAE,0BAA0B,CAAC,CAAC,CAAC,GAAG,oBAAoB,CAAC,CAAC,CAAC,CAE5G"}
|
|
@@ -22,17 +22,25 @@ export declare class LocalStorageProvider<T> {
|
|
|
22
22
|
static readonly version: string;
|
|
23
23
|
private readonly key__;
|
|
24
24
|
protected readonly logger_: import("@alwatr/logger").AlwatrLogger;
|
|
25
|
-
|
|
25
|
+
protected readonly parse_: (value: string) => T;
|
|
26
|
+
protected readonly stringify_: (value: T) => string;
|
|
27
|
+
constructor(config: LocalStorageProviderConfig<T>);
|
|
26
28
|
/**
|
|
27
29
|
* Generates the versioned storage key.
|
|
28
|
-
* @param
|
|
30
|
+
* @param config - An object containing the name and schemaVersion.
|
|
29
31
|
* @returns The versioned key string.
|
|
30
32
|
*/
|
|
31
|
-
static getKey(config:
|
|
33
|
+
static getKey(config: {
|
|
34
|
+
name: string;
|
|
35
|
+
schemaVersion: number;
|
|
36
|
+
}): string;
|
|
32
37
|
/**
|
|
33
38
|
* Manages data migration by removing all previous versions of the item.
|
|
34
39
|
*/
|
|
35
|
-
static clearPreviousStorageVersions(config:
|
|
40
|
+
static clearPreviousStorageVersions(config: {
|
|
41
|
+
name: string;
|
|
42
|
+
schemaVersion: number;
|
|
43
|
+
}): void;
|
|
36
44
|
/**
|
|
37
45
|
* Checks if a versioned item exists in localStorage for the given configuration.
|
|
38
46
|
* This static method allows checking for the existence of a specific versioned item
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-storage.provider.d.ts","sourceRoot":"","sources":["../src/local-storage.provider.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,WAAW,CAAC;AAE1D;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,oBAAoB,CAAC,CAAC;IACjC,gBAAuB,OAAO,SAAuB;IAErD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,SAAS,CAAC,QAAQ,CAAC,OAAO,wCAAC;
|
|
1
|
+
{"version":3,"file":"local-storage.provider.d.ts","sourceRoot":"","sources":["../src/local-storage.provider.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,0BAA0B,EAAC,MAAM,WAAW,CAAC;AAE1D;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,oBAAoB,CAAC,CAAC;IACjC,gBAAuB,OAAO,SAAuB;IAErD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,SAAS,CAAC,QAAQ,CAAC,OAAO,wCAAC;IAC3B,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,CAAC,CAAC;IAChD,SAAS,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,MAAM,CAAC;gBAExC,MAAM,EAAE,0BAA0B,CAAC,CAAC,CAAC;IAUjD;;;;OAIG;WACW,MAAM,CAAC,MAAM,EAAE;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM,CAAA;KAAC,GAAG,MAAM;IAI3E;;OAEG;WACW,4BAA4B,CAAC,MAAM,EAAE;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM,CAAA;KAAC,GAAG,IAAI;IAU/F;;;;;;;;;;;;OAYG;WACW,GAAG,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO;IAK9D;;;;;;;;;;;;OAYG;IACI,GAAG,IAAI,OAAO;IAIrB;;;OAGG;IACI,IAAI,IAAI,CAAC,GAAG,IAAI;IAwBvB;;OAEG;IACI,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI;IAiB5B;;OAEG;IACI,MAAM,IAAI,IAAI;CAGtB"}
|
package/dist/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* 📦 @alwatr/local-storage v9.
|
|
2
|
-
import{createLogger as z}from"@alwatr/logger";class j{static version="9.
|
|
1
|
+
/* 📦 @alwatr/local-storage v9.25.0 */
|
|
2
|
+
import{createLogger as z}from"@alwatr/logger";class j{static version="9.25.0";key__;logger_;parse_;stringify_;constructor(x){this.logger_=z(`local-storage-provider: ${x.name}, v: ${x.schemaVersion}`),this.logger_.logMethodArgs?.("constructor",{config:x}),this.key__=j.getKey(x),j.clearPreviousStorageVersions(x),this.parse_=x.parse??JSON.parse,this.stringify_=x.stringify??JSON.stringify}static getKey(x){return`${x.name}.v${x.schemaVersion}`}static clearPreviousStorageVersions(x){if(x.schemaVersion<1)return;for(let b=0;b<x.schemaVersion;b++){let q=j.getKey({name:x.name,schemaVersion:b});localStorage.removeItem(q)}}static has(x){let b=j.getKey(x);return localStorage.getItem(b)!==null}has(){return localStorage.getItem(this.key__)!==null}read(){let x=null;try{x=localStorage.getItem(this.key__)}catch(b){this.logger_.error("read","read_local_storage_error",{err:b})}if(!x)return this.logger_.logMethod?.("read//no_value"),null;try{let b=this.parse_(x);return this.logger_.logMethodFull?.("read//value",void 0,{parsedValue:b}),b}catch(b){return this.logger_.error("read","read_parse_error",{err:b}),null}}write(x){this.logger_.logMethodArgs?.("write",{value:x});let b;try{b=this.stringify_(x)}catch(q){throw this.logger_.error("write","write_stringify_error",{err:q}),Error("write_stringify_error")}try{localStorage.setItem(this.key__,b)}catch(q){this.logger_.error("write","write_local_storage_error",{err:q})}}remove(){localStorage.removeItem(this.key__)}}function E(x){return new j(x)}export{E as createLocalStorageProvider,j as LocalStorageProvider};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=B157F3AB96F5AC3164756E2164756E21
|
|
5
5
|
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/local-storage.provider.ts", "../src/facade.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import {createLogger} from '@alwatr/logger';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * A provider class for managing a specific, versioned item in localStorage.\n * It encapsulates the logic for key generation, serialization, and migration.\n *\n * @example\n * ```typescript\n * const userSettings = new LocalStorageProvider({\n * name: 'user-settings',\n * version: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport class LocalStorageProvider<T> {\n public static readonly version = __package_version__;\n\n private readonly key__: string;\n protected readonly logger_;\n\n constructor(config: LocalStorageProviderConfig) {\n this.logger_ = createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);\n this.logger_.logMethodArgs?.('constructor', {config});\n this.key__ = LocalStorageProvider.getKey(config);\n LocalStorageProvider.clearPreviousStorageVersions(config);\n }\n\n /**\n * Generates the versioned storage key.\n * @param
|
|
6
|
-
"import {LocalStorageProvider} from './local-storage.provider.js';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * Factory function to create a new LocalStorageProvider.\n *\n * @param config - The configuration for the provider.\n * @returns An instance of LocalStorageProvider.\n *\n * @example\n * ```typescript\n * const userSettings = createLocalStorageProvider({\n * name: 'user-settings',\n * schemaVersion: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport function createLocalStorageProvider<T>(config: LocalStorageProviderConfig): LocalStorageProvider<T> {\n return new LocalStorageProvider<T>(config);\n}\n"
|
|
5
|
+
"import {createLogger} from '@alwatr/logger';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * A provider class for managing a specific, versioned item in localStorage.\n * It encapsulates the logic for key generation, serialization, and migration.\n *\n * @example\n * ```typescript\n * const userSettings = new LocalStorageProvider({\n * name: 'user-settings',\n * version: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport class LocalStorageProvider<T> {\n public static readonly version = __package_version__;\n\n private readonly key__: string;\n protected readonly logger_;\n protected readonly parse_: (value: string) => T;\n protected readonly stringify_: (value: T) => string;\n\n constructor(config: LocalStorageProviderConfig<T>) {\n this.logger_ = createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);\n this.logger_.logMethodArgs?.('constructor', {config});\n this.key__ = LocalStorageProvider.getKey(config);\n LocalStorageProvider.clearPreviousStorageVersions(config);\n\n this.parse_ = config.parse ?? (JSON.parse as (value: string) => T);\n this.stringify_ = config.stringify ?? JSON.stringify;\n }\n\n /**\n * Generates the versioned storage key.\n * @param config - An object containing the name and schemaVersion.\n * @returns The versioned key string.\n */\n public static getKey(config: {name: string; schemaVersion: number}): string {\n return `${config.name}.v${config.schemaVersion}`;\n }\n\n /**\n * Manages data migration by removing all previous versions of the item.\n */\n public static clearPreviousStorageVersions(config: {name: string; schemaVersion: number}): void {\n if (config.schemaVersion < 1) return;\n\n // Iterate from v1 up to the version just before the current one and remove them.\n for (let i = 0; i < config.schemaVersion; i++) {\n const oldKey = LocalStorageProvider.getKey({name: config.name, schemaVersion: i});\n localStorage.removeItem(oldKey);\n }\n }\n\n /**\n * Checks if a versioned item exists in localStorage for the given configuration.\n * This static method allows checking for the existence of a specific versioned item\n * without instantiating the provider.\n *\n * @param config - The configuration object containing the name and schemaVersion.\n * @returns `true` if the item exists in localStorage, otherwise `false`.\n *\n * @example\n * ```typescript\n * const exists = LocalStorageProvider.has({ name: 'user-form', schemaVersion: 1 });\n * ```\n */\n public static has(config: LocalStorageProviderConfig): boolean {\n const key = LocalStorageProvider.getKey(config);\n return localStorage.getItem(key) !== null;\n }\n\n /**\n * Checks if the current versioned item exists in localStorage.\n *\n * @returns `true` if the item exists in localStorage, otherwise `false`.\n *\n * @example\n * ```typescript\n * const provider = new LocalStorageProvider({ name: 'profile', schemaVersion: 2 });\n * if (provider.has()) {\n * // Item exists\n * }\n * ```\n */\n public has(): boolean {\n return localStorage.getItem(this.key__) !== null;\n }\n\n /**\n * Reads and parses the value from localStorage.\n * If the item doesn't exist or is invalid JSON, returns null.\n */\n public read(): T | null {\n let value: string | null = null;\n\n try {\n value = localStorage.getItem(this.key__);\n } catch (err) {\n this.logger_.error('read', 'read_local_storage_error', {err});\n }\n\n if (!value) {\n this.logger_.logMethod?.('read//no_value');\n return null;\n }\n\n try {\n const parsedValue = this.parse_(value);\n this.logger_.logMethodFull?.('read//value', undefined, {parsedValue});\n return parsedValue;\n } catch (err) {\n this.logger_.error('read', 'read_parse_error', {err});\n return null;\n }\n }\n\n /**\n * Serializes and writes a value to localStorage.\n */\n public write(value: T): void {\n this.logger_.logMethodArgs?.('write', {value});\n let valueStr: string;\n try {\n valueStr = this.stringify_(value);\n } catch (err) {\n this.logger_.error('write', 'write_stringify_error', {err});\n throw new Error('write_stringify_error');\n }\n\n try {\n localStorage.setItem(this.key__, valueStr);\n } catch (err) {\n this.logger_.error('write', 'write_local_storage_error', {err});\n }\n }\n\n /**\n * Removes the item from localStorage.\n */\n public remove(): void {\n localStorage.removeItem(this.key__);\n }\n}\n",
|
|
6
|
+
"import {LocalStorageProvider} from './local-storage.provider.js';\n\nimport type {LocalStorageProviderConfig} from './type.js';\n\n/**\n * Factory function to create a new LocalStorageProvider.\n *\n * @param config - The configuration for the provider.\n * @returns An instance of LocalStorageProvider.\n *\n * @example\n * ```typescript\n * const userSettings = createLocalStorageProvider({\n * name: 'user-settings',\n * schemaVersion: 1\n * });\n *\n * // Write new settings\n * userSettings.write({ theme: 'dark', notifications: false });\n *\n * // Read the current settings\n * const currentSettings = userSettings.read();\n * console.log(currentSettings); // { theme: 'dark', notifications: false }\n * ```\n */\nexport function createLocalStorageProvider<T>(config: LocalStorageProviderConfig<T>): LocalStorageProvider<T> {\n return new LocalStorageProvider<T>(config);\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";AAAA,uBAAQ,uBAuBD,MAAM,CAAwB,OACZ,SAAU,SAEhB,MACE,
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": ";AAAA,uBAAQ,uBAuBD,MAAM,CAAwB,OACZ,SAAU,SAEhB,MACE,QACA,OACA,WAEnB,WAAW,CAAC,EAAuC,CACjD,KAAK,QAAU,EAAa,2BAA2B,EAAO,YAAY,EAAO,eAAe,EAChG,KAAK,QAAQ,gBAAgB,cAAe,CAAC,QAAM,CAAC,EACpD,KAAK,MAAQ,EAAqB,OAAO,CAAM,EAC/C,EAAqB,6BAA6B,CAAM,EAExD,KAAK,OAAS,EAAO,OAAU,KAAK,MACpC,KAAK,WAAa,EAAO,WAAa,KAAK,gBAQ/B,OAAM,CAAC,EAAuD,CAC1E,MAAO,GAAG,EAAO,SAAS,EAAO,sBAMrB,6BAA4B,CAAC,EAAqD,CAC9F,GAAI,EAAO,cAAgB,EAAG,OAG9B,QAAS,EAAI,EAAG,EAAI,EAAO,cAAe,IAAK,CAC7C,IAAM,EAAS,EAAqB,OAAO,CAAC,KAAM,EAAO,KAAM,cAAe,CAAC,CAAC,EAChF,aAAa,WAAW,CAAM,SAiBpB,IAAG,CAAC,EAA6C,CAC7D,IAAM,EAAM,EAAqB,OAAO,CAAM,EAC9C,OAAO,aAAa,QAAQ,CAAG,IAAM,KAgBhC,GAAG,EAAY,CACpB,OAAO,aAAa,QAAQ,KAAK,KAAK,IAAM,KAOvC,IAAI,EAAa,CACtB,IAAI,EAAuB,KAE3B,GAAI,CACF,EAAQ,aAAa,QAAQ,KAAK,KAAK,EACvC,MAAO,EAAK,CACZ,KAAK,QAAQ,MAAM,OAAQ,2BAA4B,CAAC,KAAG,CAAC,EAG9D,GAAI,CAAC,EAEH,OADA,KAAK,QAAQ,YAAY,gBAAgB,EAClC,KAGT,GAAI,CACF,IAAM,EAAc,KAAK,OAAO,CAAK,EAErC,OADA,KAAK,QAAQ,gBAAgB,cAAe,OAAW,CAAC,aAAW,CAAC,EAC7D,EACP,MAAO,EAAK,CAEZ,OADA,KAAK,QAAQ,MAAM,OAAQ,mBAAoB,CAAC,KAAG,CAAC,EAC7C,MAOJ,KAAK,CAAC,EAAgB,CAC3B,KAAK,QAAQ,gBAAgB,QAAS,CAAC,OAAK,CAAC,EAC7C,IAAI,EACJ,GAAI,CACF,EAAW,KAAK,WAAW,CAAK,EAChC,MAAO,EAAK,CAEZ,MADA,KAAK,QAAQ,MAAM,QAAS,wBAAyB,CAAC,KAAG,CAAC,EAChD,MAAM,uBAAuB,EAGzC,GAAI,CACF,aAAa,QAAQ,KAAK,MAAO,CAAQ,EACzC,MAAO,EAAK,CACZ,KAAK,QAAQ,MAAM,QAAS,4BAA6B,CAAC,KAAG,CAAC,GAO3D,MAAM,EAAS,CACpB,aAAa,WAAW,KAAK,KAAK,EAEtC,CC/HO,SAAS,CAA6B,CAAC,EAAgE,CAC5G,OAAO,IAAI,EAAwB,CAAM",
|
|
9
|
+
"debugId": "B157F3AB96F5AC3164756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/dist/type.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Configuration options for a local storage provider.
|
|
3
3
|
*/
|
|
4
|
-
export interface LocalStorageProviderConfig {
|
|
4
|
+
export interface LocalStorageProviderConfig<T = unknown> {
|
|
5
5
|
/**
|
|
6
6
|
* The unique name for the storage item.
|
|
7
7
|
*/
|
|
@@ -11,5 +11,17 @@ export interface LocalStorageProviderConfig {
|
|
|
11
11
|
* Start from 1 for production, 0 for development mode, and increment by 1 for each new data schema change.
|
|
12
12
|
*/
|
|
13
13
|
schemaVersion: number;
|
|
14
|
+
/**
|
|
15
|
+
* Custom parser function for deserializing the stored string.
|
|
16
|
+
* Useful for specialized data types like Maps, Sets, or Dates.
|
|
17
|
+
* Defaults to `JSON.parse`.
|
|
18
|
+
*/
|
|
19
|
+
parse?: (value: string) => T;
|
|
20
|
+
/**
|
|
21
|
+
* Custom stringifier function for serializing the value.
|
|
22
|
+
* Useful for specialized data types like Maps, Sets, or Dates.
|
|
23
|
+
* Defaults to `JSON.stringify`.
|
|
24
|
+
*/
|
|
25
|
+
stringify?: (value: T) => string;
|
|
14
26
|
}
|
|
15
27
|
//# sourceMappingURL=type.d.ts.map
|
package/dist/type.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,MAAM,WAAW,0BAA0B;
|
|
1
|
+
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../src/type.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,MAAM,WAAW,0BAA0B,CAAC,CAAC,GAAG,OAAO;IACrD;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IAEtB;;;;OAIG;IACH,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,CAAC,CAAC;IAE7B;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,MAAM,CAAC;CAClC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/local-storage",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.25.0",
|
|
4
4
|
"description": "A modern, simple, and robust solution for managing versioned JSON objects in the browser's `localStorage`. This package provides a clean, class-based API with a factory function to ensure your application's data persistence is safe, maintainable, and future-proof.",
|
|
5
5
|
"license": "MPL-2.0",
|
|
6
6
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
|
|
@@ -21,10 +21,10 @@
|
|
|
21
21
|
},
|
|
22
22
|
"sideEffects": false,
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@alwatr/logger": "9.
|
|
24
|
+
"@alwatr/logger": "9.25.0"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@alwatr/nano-build": "9.
|
|
27
|
+
"@alwatr/nano-build": "9.25.0",
|
|
28
28
|
"@alwatr/standard": "9.16.0",
|
|
29
29
|
"@alwatr/type-helper": "9.14.0",
|
|
30
30
|
"typescript": "^6.0.3"
|
|
@@ -73,5 +73,5 @@
|
|
|
73
73
|
"utility",
|
|
74
74
|
"versioning"
|
|
75
75
|
],
|
|
76
|
-
"gitHead": "
|
|
76
|
+
"gitHead": "a49ae304180faab79539b5ddfe62d18ac91a232e"
|
|
77
77
|
}
|
package/src/facade.ts
CHANGED
|
@@ -23,6 +23,6 @@ import type {LocalStorageProviderConfig} from './type.js';
|
|
|
23
23
|
* console.log(currentSettings); // { theme: 'dark', notifications: false }
|
|
24
24
|
* ```
|
|
25
25
|
*/
|
|
26
|
-
export function createLocalStorageProvider<T>(config: LocalStorageProviderConfig): LocalStorageProvider<T> {
|
|
26
|
+
export function createLocalStorageProvider<T>(config: LocalStorageProviderConfig<T>): LocalStorageProvider<T> {
|
|
27
27
|
return new LocalStorageProvider<T>(config);
|
|
28
28
|
}
|
|
@@ -26,27 +26,32 @@ export class LocalStorageProvider<T> {
|
|
|
26
26
|
|
|
27
27
|
private readonly key__: string;
|
|
28
28
|
protected readonly logger_;
|
|
29
|
+
protected readonly parse_: (value: string) => T;
|
|
30
|
+
protected readonly stringify_: (value: T) => string;
|
|
29
31
|
|
|
30
|
-
constructor(config: LocalStorageProviderConfig) {
|
|
32
|
+
constructor(config: LocalStorageProviderConfig<T>) {
|
|
31
33
|
this.logger_ = createLogger(`local-storage-provider: ${config.name}, v: ${config.schemaVersion}`);
|
|
32
34
|
this.logger_.logMethodArgs?.('constructor', {config});
|
|
33
35
|
this.key__ = LocalStorageProvider.getKey(config);
|
|
34
36
|
LocalStorageProvider.clearPreviousStorageVersions(config);
|
|
37
|
+
|
|
38
|
+
this.parse_ = config.parse ?? (JSON.parse as (value: string) => T);
|
|
39
|
+
this.stringify_ = config.stringify ?? JSON.stringify;
|
|
35
40
|
}
|
|
36
41
|
|
|
37
42
|
/**
|
|
38
43
|
* Generates the versioned storage key.
|
|
39
|
-
* @param
|
|
44
|
+
* @param config - An object containing the name and schemaVersion.
|
|
40
45
|
* @returns The versioned key string.
|
|
41
46
|
*/
|
|
42
|
-
public static getKey(config:
|
|
47
|
+
public static getKey(config: {name: string; schemaVersion: number}): string {
|
|
43
48
|
return `${config.name}.v${config.schemaVersion}`;
|
|
44
49
|
}
|
|
45
50
|
|
|
46
51
|
/**
|
|
47
52
|
* Manages data migration by removing all previous versions of the item.
|
|
48
53
|
*/
|
|
49
|
-
public static clearPreviousStorageVersions(config:
|
|
54
|
+
public static clearPreviousStorageVersions(config: {name: string; schemaVersion: number}): void {
|
|
50
55
|
if (config.schemaVersion < 1) return;
|
|
51
56
|
|
|
52
57
|
// Iterate from v1 up to the version just before the current one and remove them.
|
|
@@ -110,7 +115,7 @@ export class LocalStorageProvider<T> {
|
|
|
110
115
|
}
|
|
111
116
|
|
|
112
117
|
try {
|
|
113
|
-
const parsedValue =
|
|
118
|
+
const parsedValue = this.parse_(value);
|
|
114
119
|
this.logger_.logMethodFull?.('read//value', undefined, {parsedValue});
|
|
115
120
|
return parsedValue;
|
|
116
121
|
} catch (err) {
|
|
@@ -126,7 +131,7 @@ export class LocalStorageProvider<T> {
|
|
|
126
131
|
this.logger_.logMethodArgs?.('write', {value});
|
|
127
132
|
let valueStr: string;
|
|
128
133
|
try {
|
|
129
|
-
valueStr =
|
|
134
|
+
valueStr = this.stringify_(value);
|
|
130
135
|
} catch (err) {
|
|
131
136
|
this.logger_.error('write', 'write_stringify_error', {err});
|
|
132
137
|
throw new Error('write_stringify_error');
|
package/src/type.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Configuration options for a local storage provider.
|
|
4
4
|
*/
|
|
5
|
-
export interface LocalStorageProviderConfig {
|
|
5
|
+
export interface LocalStorageProviderConfig<T = unknown> {
|
|
6
6
|
/**
|
|
7
7
|
* The unique name for the storage item.
|
|
8
8
|
*/
|
|
@@ -13,4 +13,18 @@ export interface LocalStorageProviderConfig {
|
|
|
13
13
|
* Start from 1 for production, 0 for development mode, and increment by 1 for each new data schema change.
|
|
14
14
|
*/
|
|
15
15
|
schemaVersion: number;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Custom parser function for deserializing the stored string.
|
|
19
|
+
* Useful for specialized data types like Maps, Sets, or Dates.
|
|
20
|
+
* Defaults to `JSON.parse`.
|
|
21
|
+
*/
|
|
22
|
+
parse?: (value: string) => T;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Custom stringifier function for serializing the value.
|
|
26
|
+
* Useful for specialized data types like Maps, Sets, or Dates.
|
|
27
|
+
* Defaults to `JSON.stringify`.
|
|
28
|
+
*/
|
|
29
|
+
stringify?: (value: T) => string;
|
|
16
30
|
}
|