feat: handle API calls and caching through Vue components
BREAKING CHANGE: API calls and cache no longer made in their respective composable
This commit is contained in:
53
content/.vuepress/components/ApiLoader.vue
Normal file
53
content/.vuepress/components/ApiLoader.vue
Normal file
@@ -0,0 +1,53 @@
|
||||
<template>
|
||||
<Cache name="repos" :callback="fetchData" @cached="processCachedData" />
|
||||
<slot v-if="loading" name="loader"></slot>
|
||||
<slot v-else-if="error" name="error"></slot>
|
||||
<slot v-else>
|
||||
{{ error }}
|
||||
</slot>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import Cache from './Cache.vue';
|
||||
|
||||
import { Ref, ref } from 'vue';
|
||||
import { Observable, catchError, switchMap, throwError } from 'rxjs';
|
||||
import { fromFetch } from 'rxjs/fetch';
|
||||
|
||||
const props = defineProps({
|
||||
url: {
|
||||
default: false,
|
||||
required: true,
|
||||
type: String,
|
||||
},
|
||||
});
|
||||
const emits = defineEmits(['dataLoaded', 'dataError', 'loading']);
|
||||
|
||||
const error: Ref<Error> = ref(null);
|
||||
const loading: Ref<boolean> = ref(true);
|
||||
|
||||
const fetchData = (): Observable<any> => {
|
||||
return fromFetch(props.url).pipe(
|
||||
switchMap((response: Response) => response.json()),
|
||||
catchError((error: Error) => {
|
||||
console.error(error);
|
||||
return throwError(() => new Error(error.message));
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const processCachedData = (data: Observable<any>) => {
|
||||
data.subscribe({
|
||||
next: (response: any) => {
|
||||
loading.value = false;
|
||||
emits('dataLoaded', response);
|
||||
},
|
||||
error: (responseError: Error) => {
|
||||
loading.value = false;
|
||||
error.value = responseError;
|
||||
},
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less"></style>
|
||||
60
content/.vuepress/components/Cache.vue
Normal file
60
content/.vuepress/components/Cache.vue
Normal file
@@ -0,0 +1,60 @@
|
||||
<template>
|
||||
<slot />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Ref, ref } from 'vue';
|
||||
import { Observable, of } from 'rxjs';
|
||||
|
||||
const props = defineProps({
|
||||
name: {
|
||||
required: true,
|
||||
type: String,
|
||||
},
|
||||
callback: {
|
||||
required: true,
|
||||
type: Function,
|
||||
},
|
||||
lifetime: {
|
||||
default: 1000 * 60 * 60, // one hour
|
||||
required: false,
|
||||
type: Number,
|
||||
},
|
||||
});
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
const storeInCache = (data: Observable<any>, name: string): Observable<any> => {
|
||||
data.subscribe({
|
||||
next: (response) => {
|
||||
localStorage.setItem(name, JSON.stringify(response));
|
||||
localStorage.setItem(name + '-timestamp', `${Date.now()}`);
|
||||
},
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
const dataFromCache: Ref<Observable<any>> = ref(null);
|
||||
if (isDataOutdated(props.name)) {
|
||||
emits('cached', storeInCache(props.callback(), props.name));
|
||||
} else {
|
||||
console.log('Sending cached data');
|
||||
let data = localStorage.getItem(props.name);
|
||||
try {
|
||||
emits('cached', of(JSON.parse(data)));
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`Could not parse ${JSON.stringify(
|
||||
dataFromCache
|
||||
)}: ${err}. Fetching again data from API.`
|
||||
);
|
||||
emits('cached', storeInCache(props.callback(), props.name));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -12,7 +12,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { GithubRepo } from '../composables/github';
|
||||
import { GithubRepo } from '../../composables/github';
|
||||
import { PropType } from 'vue';
|
||||
const props = defineProps({
|
||||
repo: Object as PropType<GithubRepo>,
|
||||
@@ -21,7 +21,7 @@ const props = defineProps({
|
||||
|
||||
<style lang="less">
|
||||
@import 'node_modules/nord/src/lesscss/nord.less';
|
||||
@import '../styles/classes.less';
|
||||
@import '../../styles/classes.less';
|
||||
|
||||
.githubRepo {
|
||||
max-width: 35rem;
|
||||
50
content/.vuepress/components/GitRepos/ListRepositories.vue
Normal file
50
content/.vuepress/components/GitRepos/ListRepositories.vue
Normal file
@@ -0,0 +1,50 @@
|
||||
<template>
|
||||
<ApiLoader :url="fetchUrl" @dataLoaded="filterRepos">
|
||||
<GithubRepository :repo="repo" type="repositories" v-for="repo in repos" />
|
||||
</ApiLoader>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { PropType, Ref, ref } from 'vue';
|
||||
import { GithubRepo } from '../../composables/github';
|
||||
import GithubRepository from './GithubRepository.vue';
|
||||
const props = defineProps({
|
||||
sortBy: {
|
||||
default: 'pushed_at',
|
||||
required: false,
|
||||
type: String as PropType<'stars' | 'forks' | 'pushed_at'>,
|
||||
},
|
||||
user: {
|
||||
default: '',
|
||||
required: true,
|
||||
type: String,
|
||||
},
|
||||
limit: {
|
||||
default: 5,
|
||||
required: false,
|
||||
type: Number,
|
||||
},
|
||||
});
|
||||
|
||||
let repos: Ref<GithubRepo[]> = ref(null);
|
||||
|
||||
const fetchUrl = `https://api.github.com/users/${props.user}/repos?per_page=100`;
|
||||
|
||||
const filterRepos = (response: GithubRepo[]) => {
|
||||
repos.value = response
|
||||
.sort((a, b) => {
|
||||
if (props.sortBy === 'stars') {
|
||||
return b.stargazers_count - a.stargazers_count;
|
||||
}
|
||||
if (props.sortBy === 'pushed_at') {
|
||||
const dateA = new Date(a.pushed_at);
|
||||
const dateB = new Date(b.pushed_at);
|
||||
return dateB.getTime() - dateA.getTime();
|
||||
}
|
||||
return b.forks_count - a.forks_count;
|
||||
})
|
||||
.slice(0, +props.limit);
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less"></style>
|
||||
@@ -1,44 +0,0 @@
|
||||
<template>
|
||||
<div v-if="githubRepos && githubRepos.length > 0">
|
||||
<div v-for="repo in githubRepos">
|
||||
<GithubRepository :repo="repo" v-for="repo in githubRepos" />
|
||||
</div>
|
||||
</div>
|
||||
<p v-else>Error: {{ error }}</p>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, Ref } from 'vue';
|
||||
import { readFromCache } from '../composables/cache';
|
||||
import {
|
||||
GithubError,
|
||||
GithubRepo,
|
||||
getLatestRepositories,
|
||||
} from '../composables/github';
|
||||
|
||||
let githubRepos: Ref<GithubRepo[]> = ref(null);
|
||||
let error: Ref<GithubError> = ref(null);
|
||||
const getRepositories = () => {
|
||||
return getLatestRepositories('phundrak', 5);
|
||||
};
|
||||
|
||||
// TODO: Cache all repositories and not just these
|
||||
readFromCache<GithubRepo[]>('latestRepos', getRepositories).subscribe({
|
||||
next: (repos: GithubRepo[]) => {
|
||||
console.log('Received repos:', repos);
|
||||
githubRepos.value = repos;
|
||||
error.value = null;
|
||||
},
|
||||
error: (errorResponse: GithubError) => {
|
||||
githubRepos.value = null;
|
||||
error.value = errorResponse;
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="less">
|
||||
@import '../styles/classes.less';
|
||||
.repositories {
|
||||
margin: 2rem auto;
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user