2019-07-26 14:14:01 +02:00
|
|
|
import {Toast} from "native-base";
|
|
|
|
|
2019-08-06 13:28:11 +02:00
|
|
|
/**
|
|
|
|
* Class used to get json data from the web
|
|
|
|
*/
|
2019-07-26 14:14:01 +02:00
|
|
|
export default class WebDataManager {
|
|
|
|
|
2019-08-06 13:28:11 +02:00
|
|
|
FETCH_URL: string;
|
|
|
|
lastDataFetched: Object = {};
|
2019-07-26 14:14:01 +02:00
|
|
|
|
|
|
|
|
|
|
|
constructor(url) {
|
|
|
|
this.FETCH_URL = url;
|
|
|
|
}
|
|
|
|
|
2019-08-06 13:28:11 +02:00
|
|
|
/**
|
|
|
|
* Read data from FETCH_URL and return it.
|
|
|
|
* If no data was found, returns an empty object
|
|
|
|
*
|
|
|
|
* @return {Promise<Object>}
|
|
|
|
*/
|
2019-07-26 14:14:01 +02:00
|
|
|
async readData() {
|
2019-08-06 13:28:11 +02:00
|
|
|
let fetchedData: Object = {};
|
2019-07-26 14:14:01 +02:00
|
|
|
try {
|
|
|
|
let response = await fetch(this.FETCH_URL);
|
|
|
|
fetchedData = await response.json();
|
|
|
|
} catch (error) {
|
|
|
|
console.log('Could not read FetchedData from server');
|
|
|
|
console.log(error);
|
2019-08-08 18:40:42 +02:00
|
|
|
throw new Error('Could not read FetchedData from server');
|
2019-07-26 14:14:01 +02:00
|
|
|
}
|
|
|
|
this.lastDataFetched = fetchedData;
|
|
|
|
return fetchedData;
|
|
|
|
}
|
|
|
|
|
2019-08-06 13:28:11 +02:00
|
|
|
/**
|
|
|
|
* Detects if the fetched data is not an empty object
|
|
|
|
*
|
|
|
|
* @return
|
|
|
|
*/
|
|
|
|
isDataObjectValid(): boolean {
|
2019-07-26 14:14:01 +02:00
|
|
|
return Object.keys(this.lastDataFetched).length > 0;
|
|
|
|
}
|
|
|
|
|
2019-08-06 13:28:11 +02:00
|
|
|
/**
|
|
|
|
* Show a toast message depending on the validity of the fetched data
|
|
|
|
*
|
|
|
|
* @param successString
|
|
|
|
* @param errorString
|
|
|
|
*/
|
2019-07-26 14:14:01 +02:00
|
|
|
showUpdateToast(successString, errorString) {
|
|
|
|
let isSuccess = this.isDataObjectValid();
|
2019-08-05 22:55:45 +02:00
|
|
|
if (!isSuccess) {
|
|
|
|
Toast.show({
|
|
|
|
text: isSuccess ? successString : errorString,
|
|
|
|
buttonText: 'OK',
|
|
|
|
type: isSuccess ? "success" : "danger",
|
|
|
|
duration: 2000
|
|
|
|
});
|
|
|
|
}
|
2019-07-26 14:14:01 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|