1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-30 08:09:15 +01:00
metamask-extension/app/scripts/lib/network-store.js

64 lines
1.4 KiB
JavaScript
Raw Normal View History

import log from 'loglevel';
import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout';
const fetchWithTimeout = getFetchWithTimeout(30000);
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
*/
export default class ReadOnlyNetworkStore {
2020-11-03 00:41:28 +01:00
constructor() {
this._initialized = false;
this._initializing = this._init();
this._state = undefined;
}
/**
2020-11-03 00:41:28 +01:00
* Declares this store as compatible with the current browser
*/
isSupported = true;
/**
* Initializes by loading state from the network
*/
2020-11-03 00:41:28 +01:00
async _init() {
try {
const response = await fetchWithTimeout(FIXTURE_SERVER_URL);
if (response.ok) {
this._state = await response.json();
}
} catch (error) {
log.debug(`Error loading network state: '${error.message}'`);
} finally {
this._initialized = true;
}
}
/**
* Returns state
* @returns {Promise<object>}
*/
2020-11-03 00:41:28 +01:00
async get() {
if (!this._initialized) {
await this._initializing;
}
return this._state;
}
/**
* Set state
* @param {Object} state - The state to set
* @returns {Promise<void>}
*/
2020-11-03 00:41:28 +01:00
async set(state) {
if (!this._initialized) {
await this._initializing;
}
this._state = state;
}
}