2023-05-08 01:01:17 +00:00
|
|
|
<template>
|
|
|
|
<slot />
|
|
|
|
</template>
|
|
|
|
|
|
|
|
<script setup lang="ts">
|
2023-11-03 17:38:03 +00:00
|
|
|
import { Observable, of, tap } from 'rxjs';
|
2023-05-08 01:01:17 +00:00
|
|
|
|
|
|
|
const props = defineProps({
|
|
|
|
name: {
|
|
|
|
required: true,
|
|
|
|
type: String,
|
|
|
|
},
|
|
|
|
callback: {
|
|
|
|
required: true,
|
|
|
|
type: Function,
|
|
|
|
},
|
|
|
|
lifetime: {
|
|
|
|
default: 1000 * 60 * 60, // one hour
|
|
|
|
required: false,
|
|
|
|
type: Number,
|
|
|
|
},
|
2023-05-08 10:44:12 +00:00
|
|
|
alreadyKnownData: {
|
2023-05-08 09:19:41 +00:00
|
|
|
default: null,
|
|
|
|
type: Object,
|
|
|
|
},
|
2023-05-08 01:01:17 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const emits = defineEmits(['cached']);
|
|
|
|
|
|
|
|
const isDataOutdated = (name: string): boolean => {
|
|
|
|
const lastUpdated: number = +localStorage.getItem(name + '-timestamp');
|
|
|
|
const elapsedTime: number = Date.now() - lastUpdated;
|
|
|
|
return elapsedTime > props.lifetime;
|
|
|
|
};
|
|
|
|
|
2023-05-08 09:19:41 +00:00
|
|
|
const storeInCache = (
|
|
|
|
callback: Function,
|
|
|
|
data: any,
|
2023-11-03 17:38:03 +00:00
|
|
|
name: string,
|
2023-05-08 09:19:41 +00:00
|
|
|
): Observable<any> => {
|
|
|
|
let response: Observable<any> = data ? of(data) : callback();
|
2023-11-03 17:38:03 +00:00
|
|
|
return response.pipe(
|
|
|
|
tap((response) => {
|
2023-05-08 01:01:17 +00:00
|
|
|
localStorage.setItem(name, JSON.stringify(response));
|
|
|
|
localStorage.setItem(name + '-timestamp', `${Date.now()}`);
|
2023-11-03 17:38:03 +00:00
|
|
|
}),
|
|
|
|
);
|
2023-05-08 01:01:17 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if (isDataOutdated(props.name)) {
|
2023-05-08 10:44:12 +00:00
|
|
|
emits(
|
|
|
|
'cached',
|
2023-11-03 17:38:03 +00:00
|
|
|
storeInCache(props.callback, props.alreadyKnownData, props.name),
|
2023-05-08 10:44:12 +00:00
|
|
|
);
|
2023-05-08 01:01:17 +00:00
|
|
|
} else {
|
|
|
|
let data = localStorage.getItem(props.name);
|
|
|
|
try {
|
|
|
|
emits('cached', of(JSON.parse(data)));
|
|
|
|
} catch (err) {
|
2023-05-08 08:36:19 +00:00
|
|
|
console.error(`Could not parse data found in cache: ${err}`);
|
2023-05-08 10:44:12 +00:00
|
|
|
emits(
|
|
|
|
'cached',
|
2023-11-03 17:38:03 +00:00
|
|
|
storeInCache(props.callback, props.alreadyKnownData, props.name),
|
2023-05-08 10:44:12 +00:00
|
|
|
);
|
2023-05-08 01:01:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
</script>
|