Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Typescript to encapsulate local storage

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to use Typescript to encapsulate local storage. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Local storage usage scenario

Storage of token after user login

Storage of user information

Communication between different pages

Persistence of project state management, such as redux persistence, vuex persistence, etc.

Performance optimization, etc.

...

Problems in use

The official api is not very friendly (too lengthy) and is stored in the form of strings, and data type conversion is required for access.

LocalStorage.setItem (key, value)

...

Unable to set expiration time

Stored in clear text, some relatively private information can be easily looked up in the browser.

Sharing local storage space with the same origin project may cause data confusion

Solution

The solution to the above problem is encapsulated in a class and exposed to the user directly in the form of a simple interface. The following functions will be encapsulated in the class

Conversion of data types

Expiration time

data encryption

A unified naming convention

Function implementation / / storage.tsenum StorageType {l = 'localStorage', s =' sessionStorage'} class MyStorage {storage: Storage constructor (type: StorageType) {this.storage = type = = StorageType.l? Window.localStorage: window.sessionStorage} set (key: string, value: any) {const data = JSON.stringify (value) this.storage.setItem (key Data)} get (key: string) {const value = this.storage.getItem (key) if (value) {return JSON.parse (value)} delete (key: string) {this.storage.removeItem (key)} clear () {this.storage.clear ()} const LStorage = new MyStorage (StorageType.l) const SStorage = new MyStorage (StorageType.s) export {LStorage, SStorage}

The above code simply implements the basic functions of local storage, and internally completes the data type conversion operation during access, which is used as follows:

Import {LStorage, SStorage} from'. / storage'...LStorage.set ('data', {name:' zhangsan'}) LStorage.get ('data') / / {name:' zhangsan'} join expiration time

The idea of setting the expiration time is as follows: add the field of expires to the data when set, record the storage time of the data, and compare the extracted expires with the current time when get. If the current time is greater than expires, it means that the data record has expired. The data record is cleared at this time, and the null,expires type can be boolean type and number type. The default is false, that is, the expiration time is not set, when the user sets it to true. The default expiration time is 1 year. When the user sets it to a specific value, the expiration time is the value set by the user. The code is as follows:

Interface IStoredItem {value: any expires?: number}... set (key: string, value: any, expires: boolean | number = false,) {const source: IStoredItem = {value: null} if (expires) {/ / default setting expires for one year This can be adjusted according to the actual situation source.expires = new Date () .getTime () + (expires = true? 1000 * 60 * 24 * 24365: expires)} source.value = value const data = JSON.stringify (source) this.storage.setItem (key) Data)} get (key: string) {const value = this.storage.getItem (key) if (value) {const source: IStoredItem = JSON.parse (value) const expires = source.expires const now = new Date (). GetTime () if (expires & & now > expires) {this.delete (key) return null} return source.value}} add data encryption

Crypto-js package is used for encryption, and two private methods of encrypt,decrypt are encapsulated in the class to handle data encryption and decryption. Of course, users can also set whether to encrypt the data through the encryption field, which defaults to true, that is, there is encryption by default. In addition, the current environment can be obtained through process.env.NODE_ENV. If it is a development environment, it is not encrypted to facilitate development and debugging. The code is implemented as follows:

Import CryptoJS from 'crypto-js'const SECRET_KEY =' nkldsx@#45#VDss9'const IS_DEV = process.env.NODE_ENV = = 'development'...class MyStorage {... Private encrypt (data: string) {return CryptoJS.AES.encrypt (data, SECRET_KEY). ToString ()} private decrypt (data: string) {const bytes = CryptoJS.AES.decrypt (data, SECRET_KEY) return bytes.toString (CryptoJS.enc.Utf8)} set (key: string, value: any, expires: boolean | number = false Encryption = true) {const source: IStoredItem = {value: null} if (expires) {source.expires = new Date () .getTime () + (expires = = true? 1000 * 60 * 24 * expires)} source.value = value const data = JSON.stringify (source) this.storage.setItem (key, IS_DEV? Data: encryption? This.encrypt (data): data)} get (key: string, encryption = true) {const value = this.storage.getItem (key) if (value) {const source: IStoredItem = JSON.parse (value) const expires = source.expires const now = new Date () getTime () if (expires & & now > expires) {this.delete (key) return null} return IS_DEV? Source.value: encryption? This.decrypt (source.value): source.value} add naming convention

You can standardize naming by adding a prefix to key, such as the composite key of project name _ version number _ key type. This naming convention can be set freely, either through a constant setting or by obtaining name and version in package.json. The code is as follows:

Const config = require ('.. /.. / package.json') const PREFIX = config.name +'_'+ config.version +'_ '... class MyStorage {/ / synthetic key private synthesisKey (key: string) {return PREFIX + key}. Set (key: string, value: any, expires: boolean | number = false, encryption = true) {. This.storage.setItem (this.synthesisKey (key), IS_DEV? Data: encryption? This.encrypt (data): data)} get (key: string, encryption = true) {const value = this.storage.getItem (this.synthesisKey (key)).}} complete code import CryptoJS from 'crypto-js'const config = require ('.. / package.json') enum StorageType {l = 'localStorage' S = 'sessionStorage'} interface IStoredItem {value: any expires?: number} const SECRET_KEY =' nkldsx@#45#VDss9'const PREFIX = config.name +'_'+ config.version +'_ 'const IS_DEV = process.env.NODE_ENV = =' development'class MyStorage {storage: Storage constructor (type: StorageType) {this.storage = type = StorageType.l? Window.localStorage: window.sessionStorage} private encrypt (data: string) {return CryptoJS.AES.encrypt (data, SECRET_KEY). ToString ()} private decrypt (data: string) {const bytes = CryptoJS.AES.decrypt (data, SECRET_KEY) return bytes.toString (CryptoJS.enc.Utf8)} private synthesisKey (key: string) {return PREFIX + key} set (key: string, value: any, expires: boolean | number = false Encryption = true) {const source: IStoredItem = {value: null} if (expires) {source.expires = new Date () .getTime () + (expires = = true? 1000 * 60 * 24 * expires)} source.value = value const data = JSON.stringify (source) this.storage.setItem (this.synthesisKey (key), IS_DEV? Data: encryption? This.encrypt (data): data)} get (key: string Encryption = true) {const value = this.storage.getItem (this.synthesisKey (key)) if (value) {const source: IStoredItem = JSON.parse (value) const expires = source.expires const now = new Date (). GetTime () if (expires & & now > expires) {this.delete (key) return null} return IS_DEV? Source.value: encryption? This.decrypt (source.value): source.value}} delete (key: string) {this.storage.removeItem (this.synthesisKey (key))} clear () {this.storage.clear ()} const LStorage = new MyStorage (StorageType.l) const SStorage = new MyStorage (StorageType.s) export {LStorage, SStorage} Thank you for reading! This is the end of the article on "how to use Typescript to encapsulate local storage". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report