2020-01-09 04:34:58 +01:00
|
|
|
import log from 'loglevel'
|
2019-12-11 18:26:20 +01:00
|
|
|
|
|
|
|
const FIXTURE_SERVER_HOST = 'localhost'
|
|
|
|
const FIXTURE_SERVER_PORT = 12345
|
|
|
|
const FIXTURE_SERVER_URL = `http://${FIXTURE_SERVER_HOST}:${FIXTURE_SERVER_PORT}/state.json`
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A read-only network-based storage wrapper
|
|
|
|
*/
|
2020-05-06 00:19:38 +02:00
|
|
|
export default class ReadOnlyNetworkStore {
|
2019-12-11 18:26:20 +01:00
|
|
|
constructor () {
|
|
|
|
this._initialized = false
|
|
|
|
this._initializing = this._init()
|
|
|
|
this._state = undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Declares this store as compatible with the current browser
|
|
|
|
*/
|
|
|
|
isSupported = true
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Initializes by loading state from the network
|
|
|
|
*/
|
|
|
|
async _init () {
|
|
|
|
try {
|
2020-04-15 19:23:27 +02:00
|
|
|
const response = await window.fetch(FIXTURE_SERVER_URL)
|
2019-12-11 18:26:20 +01:00
|
|
|
if (response.ok) {
|
|
|
|
this._state = await response.json()
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
log.debug(`Error loading network state: '${error.message}'`)
|
|
|
|
} finally {
|
|
|
|
this._initialized = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns state
|
2020-01-13 19:36:36 +01:00
|
|
|
* @returns {Promise<object>}
|
2019-12-11 18:26:20 +01:00
|
|
|
*/
|
|
|
|
async get () {
|
|
|
|
if (!this._initialized) {
|
|
|
|
await this._initializing
|
|
|
|
}
|
|
|
|
return this._state
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Set state
|
2020-01-13 19:36:36 +01:00
|
|
|
* @param {Object} state - The state to set
|
|
|
|
* @returns {Promise<void>}
|
2019-12-11 18:26:20 +01:00
|
|
|
*/
|
|
|
|
async set (state) {
|
|
|
|
if (!this._initialized) {
|
|
|
|
await this._initializing
|
|
|
|
}
|
|
|
|
this._state = state
|
|
|
|
}
|
|
|
|
}
|