| 1 | /** |
| 2 | * MemoryStorage is a wrapper around mw.SafeStorage objects. |
| 3 | * |
| 4 | * It provides two mechanisms to improve their behavior when the underlying storage mechanism fails |
| 5 | * (e.g. quota exceeded): |
| 6 | * |
| 7 | * - Duplicating their contents in memory, so that the storage can be relied on before the page has |
| 8 | * been reloaded. |
| 9 | * - Storing all keys in a single underlying key, to make the stores are atomic: either all values |
| 10 | * are stored or none. |
| 11 | * |
| 12 | * This has two additional consequences which are convenient for our use case: |
| 13 | * |
| 14 | * - All keys share the same expiry time, removing the need to specify it repeatedly. |
| 15 | * - When multiple processes try to write the same keys, all keys are overwritten, so that we don't |
| 16 | * have to worry about inconsistent data. |
| 17 | * |
| 18 | * @example |
| 19 | * var sessionStorage = new MemoryStorage( mw.storage.session, 'myprefix' ); |
| 20 | * var localStorage = new MemoryStorage( mw.storage, 'myprefix' ); |
| 21 | */ |
| 22 | class MemoryStorage { |
| 23 | /** |
| 24 | * @param {mw.SafeStorage} backend |
| 25 | * @param {string} key Key name to store under |
| 26 | * @param {number} [expiry] Number of seconds after which this item can be deleted |
| 27 | */ |
| 28 | constructor( backend, key, expiry ) { |
| 29 | this.backend = backend; |
| 30 | this.key = key; |
| 31 | this.expiry = expiry; |
| 32 | |
| 33 | this.data = this.backend.getObject( this.key ) || {}; |
| 34 | } |
| 35 | |
| 36 | get( key ) { |
| 37 | if ( Object.prototype.hasOwnProperty.call( this.data, key ) ) { |
| 38 | return this.data[ key ]; |
| 39 | } |
| 40 | return null; |
| 41 | } |
| 42 | |
| 43 | set( key, value ) { |
| 44 | this.data[ key ] = value; |
| 45 | this.backend.setObject( this.key, this.data, this.expiry ); |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | remove( key ) { |
| 50 | delete this.data[ key ]; |
| 51 | if ( Object.keys( this.data ).length === 0 ) { |
| 52 | this.backend.remove( this.key ); |
| 53 | } else { |
| 54 | this.backend.setObject( this.key, this.data, this.expiry ); |
| 55 | } |
| 56 | return true; |
| 57 | } |
| 58 | |
| 59 | clear() { |
| 60 | this.data = {}; |
| 61 | this.backend.remove( this.key ); |
| 62 | } |
| 63 | |
| 64 | // For compatibility with mw.SafeStorage API |
| 65 | getObject( key ) { |
| 66 | return this.get( key ); |
| 67 | } |
| 68 | |
| 69 | // For compatibility with mw.SafeStorage API |
| 70 | setObject( key, value ) { |
| 71 | return this.set( key, value ); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | module.exports = MemoryStorage; |