File size: 2,257 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
/*
Defines the options used for the @wp/data persistence plugin,
which include a persistent storage implementation to add data expiration handling.
*/
const storageKey = 'WPCOM_7_DAYS_PERSISTENCE';
const PERSISTENCE_INTERVAL = 7 * 24 * 3600000; // days * hours in days * ms in hour
const STORAGE_KEY = storageKey;
const STORAGE_TS_KEY = storageKey + '_TS';
// A plain object fallback if localStorage is not available
const objStore: { [ key: string ]: string } = {};
const objStorage: Pick< Storage, 'getItem' | 'setItem' | 'removeItem' > = {
getItem( key ) {
if ( objStore.hasOwnProperty( key ) ) {
return objStore[ key ];
}
return null;
},
setItem( key, value ) {
objStore[ key ] = String( value );
},
removeItem( key ) {
delete objStore[ key ];
},
};
// Make sure localStorage support exists
const localStorageSupport = (): boolean => {
try {
window.localStorage.setItem( 'WP_ONBOARD_TEST', '1' );
window.localStorage.removeItem( 'WP_ONBOARD_TEST' );
return true;
} catch ( e ) {
return false;
}
};
// Choose the right storage implementation
const storageHandler = localStorageSupport() ? window.localStorage : objStorage;
// Persisted data expires after seven days
const isNotExpired = ( timestampStr: string ): boolean => {
const timestamp = Number( timestampStr );
return Boolean( timestamp ) && timestamp + PERSISTENCE_INTERVAL > Date.now();
};
// Check for "fresh" query param
const hasFreshParam = (): boolean => {
return new URLSearchParams( window.location.search ).has( 'fresh' );
};
// Handle data expiration by providing a storage object override to the @wp/data persistence plugin.
const storage: Pick< Storage, 'getItem' | 'setItem' > = {
getItem( key ) {
const timestamp = storageHandler.getItem( STORAGE_TS_KEY );
if ( timestamp && isNotExpired( timestamp ) && ! hasFreshParam() ) {
return storageHandler.getItem( key );
}
storageHandler.removeItem( STORAGE_KEY );
storageHandler.removeItem( STORAGE_TS_KEY );
return null;
},
setItem( key, value ) {
storageHandler.setItem( STORAGE_TS_KEY, JSON.stringify( Date.now() ) );
storageHandler.setItem( key, value );
},
};
const persistOptions = {
storageKey: STORAGE_KEY,
storage,
};
export default persistOptions;
|