1. 程式人生 > >cache 快取的處理

cache 快取的處理

/** * 資料快取cache檔案 */
/** * cache策略 * * 快取key相關 * 1. 自定義key * 2. 通過url相關來判斷是否相同key (需要和http請求模組放一起寫) * 1)非嚴格模式,通過對比url來判斷 * 2)嚴格模式,通過對比url、請求方式、引數來判斷是否為相同的key * * 快取資料儲存方式方式,強cache還是弱cache * 1)localstorage、indexDB
* 2) sessionstorage、JS物件 * * 2. 是否需要設定快取資料過期時間 * 1) 需要設定快取時間 * 2) 不需要設定快取時間 預設為-1,不檢測 * * 3. 快取字首,通過字首區別不同key * * 快取資料格式 * { * expires: 1504003903042 || -1, // 設定過期時間 * data: value // 源資料 * } * */
import
{ lstorage, sstorage } from '@/utils/storage' import { getKey } from '@/utils/utils'
/** * 快取建構函式 */ function Cache ( options = {}) { // 基礎配置項 const conf = { // 可用的快取過期時間示例 // expires: 60 * 60 * 1000, // 快取過期時間1小時 // expires: 60 * 1000, // 快取過期時間1分鐘
expires: - 1, // 快取時間設定為 -1,代表不檢測快取時間 prefix: '', // 快取key字首 type: 1 // 1: 強快取型別, 2: 弱快取型別 } // 設定物件屬性 this. options = Object. assign( conf, options) }
/** * 新建立cache物件 */ Cache. create = function ( options = {}) { return new Cache( options) }
/** * 快取資料 * key可以是物件字面量,也可以是字串 * val 需要快取的值 * options 配置項 */ Cache. prototype. set = function ( key, val, options = {}) { // 更新配置項 options = Object. assign( this. options, options)
// 拼接字首,獲取cache MD5 key key = getKey( options. prefix + key)
// 判斷使用者是否需要設定快取時間 // 設定快取時間,則將過期時間持久化,否則持久化-1 if ( options. expires !== - 1) { options. expires = new Date(). getTime() + options. expires }
// 構造儲存資料結構 val = { expires: options. expires, // 設定過期時間 data: val // 源資料 }
// 判斷儲存型別,強快取(localStorage) || 弱快取(sessionStorage)儲存 options. type === 1 ? lstorage. set( key, val) : sstorage. set( key, val) }
/** * 獲取快取資訊 */ Cache. prototype. get = function ( key, options = {}) { // 更新配置項 options = Object. assign( this. options, options)
// 拼接字首,獲取cache MD5 key key = util. getKey( options. prefix + key)
// 判斷資料是否為強快取型別 let val = options. type === 1 ? lstorage. get( key) : sstorage. get( key)
// 判斷存在快取值,並且未設定快取時間,(預設快取值為 -1),返回源資料 if ( val && options. expires === - 1) return val. data
// 判斷存在設定快取值,(快取值不為 -1),快取時間過期則返回false,不過期則返回源資料 if ( val && options. expires !== - 1 && val. expires > new Date(). getTime()) return val. data
// 資料來源不存在 || 非設定快取 || 快取過期,返回 undefined return undefined }
/** * 刪除快取資料 */ Cache. prototype. remove = function ( key, options = {}) { // 更新配置項 options = Object. assign( this. options, options)
// 獲取cache MD5 key key = util. getKey( options. prefix + key)
// 判斷儲存型別,移除強快取(localStorage) || 弱快取(sessionStorage)儲存 options. type === 1 ? lstorage. remove( key) : sstorage. remove( key) }
/** * 更新快取配置檔案 */ Cache. prototype. config = function ( options = {}) { // 更新配置項 this. options = Object. assign( this. options, options) }
// 例項化Cache物件 let cache = new Cache()
export { cache, Cache }