2021-01-15 00:29:07 +01:00
|
|
|
/***
|
|
|
|
* Saves all the features that are passed in to localstorage, so they can be retrieved on the next run
|
|
|
|
*
|
|
|
|
* Technically, more an Actor then a featuresource, but it fits more neatly this ay
|
|
|
|
*/
|
|
|
|
import FeatureSource from "./FeatureSource";
|
|
|
|
import {UIEventSource} from "../UIEventSource";
|
2021-08-07 23:11:34 +02:00
|
|
|
import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig";
|
2021-01-15 00:29:07 +01:00
|
|
|
|
|
|
|
export default class LocalStorageSaver implements FeatureSource {
|
|
|
|
public static readonly storageKey: string = "cached-features";
|
|
|
|
public readonly features: UIEventSource<{ feature: any; freshness: Date }[]>;
|
|
|
|
|
2021-04-23 12:55:38 +02:00
|
|
|
public readonly name = "LocalStorageSaver";
|
|
|
|
|
2021-01-15 01:57:46 +01:00
|
|
|
constructor(source: FeatureSource, layout: UIEventSource<LayoutConfig>) {
|
2021-01-15 00:29:07 +01:00
|
|
|
this.features = source.features;
|
|
|
|
|
2021-06-30 16:02:46 +02:00
|
|
|
this.features.addCallbackAndRunD(features => {
|
2021-04-17 15:42:22 +02:00
|
|
|
const now = new Date().getTime()
|
|
|
|
features = features.filter(f => layout.data.cacheTimeout > Math.abs(now - f.freshness.getTime())/1000)
|
|
|
|
|
2021-04-17 23:36:46 +02:00
|
|
|
|
2021-01-15 00:29:07 +01:00
|
|
|
if(features.length == 0){
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2021-01-15 01:57:46 +01:00
|
|
|
const key = LocalStorageSaver.storageKey+layout.data.id
|
|
|
|
localStorage.setItem(key, JSON.stringify(features));
|
|
|
|
console.log("Saved ",features.length, "elements to",key)
|
2021-01-15 00:29:07 +01:00
|
|
|
} catch (e) {
|
|
|
|
console.warn("Could not save the features to local storage:", e)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|