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:
Lucien Cartier-Tilet 2023-05-08 03:01:17 +02:00
parent 08825d870b
commit 0a1e9536cd
Signed by: phundrak
GPG Key ID: BD7789E705CB8DCA
9 changed files with 176 additions and 134 deletions

View File

@ -1,15 +1,17 @@
import { defineClientConfig } from '@vuepress/client'; import { defineClientConfig } from '@vuepress/client';
import PreviewImage from './components/PreviewImage.vue';
import ResponsiveImage from './components/ResponsiveImage.vue'; import ResponsiveImage from './components/ResponsiveImage.vue';
import LatestRepositories from './components/LatestRepositories.vue'; import ListRepositories from './components/GitRepos/ListRepositories.vue';
import GithubRepository from './components/GithubRepository.vue'; import GithubRepository from './components/GitRepos/GithubRepository.vue';
import ApiLoader from './components/ApiLoader.vue';
import Cache from './components/Cache.vue';
export default defineClientConfig({ export default defineClientConfig({
enhance({ app }) { enhance({ app }) {
app.component('PreviewImage', PreviewImage);
app.component('ResponsiveImage', ResponsiveImage); app.component('ResponsiveImage', ResponsiveImage);
app.component('LatestRepositories', LatestRepositories); app.component('ListRepositories', ListRepositories);
app.component('GithubRepository', GithubRepository); app.component('GithubRepository', GithubRepository);
app.component('ApiLoader', ApiLoader);
app.component('Cache', Cache);
}, },
setup() {}, setup() {},
layouts: {}, layouts: {},

View 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>

View 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>

View File

@ -12,7 +12,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { GithubRepo } from '../composables/github'; import { GithubRepo } from '../../composables/github';
import { PropType } from 'vue'; import { PropType } from 'vue';
const props = defineProps({ const props = defineProps({
repo: Object as PropType<GithubRepo>, repo: Object as PropType<GithubRepo>,
@ -21,7 +21,7 @@ const props = defineProps({
<style lang="less"> <style lang="less">
@import 'node_modules/nord/src/lesscss/nord.less'; @import 'node_modules/nord/src/lesscss/nord.less';
@import '../styles/classes.less'; @import '../../styles/classes.less';
.githubRepo { .githubRepo {
max-width: 35rem; max-width: 35rem;

View 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>

View File

@ -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>

View File

@ -1,46 +0,0 @@
import { Observable, of } from 'rxjs';
const cacheAgeLimitInMilliseconds = 1000 * 60 * 60;
export function isDataOutdated(name: string): boolean {
const lastUpdated: number = +localStorage.getItem(name + '-timestamp');
const now: number = Date.now();
const elapsedTime: number = now - lastUpdated;
return elapsedTime > cacheAgeLimitInMilliseconds;
}
export function storeInCache<T>(
data: Observable<T>,
name: string
): Observable<T> {
data.subscribe({
next: (response: T) => {
localStorage.setItem(name, JSON.stringify(response));
localStorage.setItem(name + '-timestamp', `${Date.now()}`);
},
});
return data;
}
export function readFromCache<T>(
name: string,
callback: () => Observable<T>
): Observable<T> {
let data: Observable<T>;
if (isDataOutdated(name)) {
data = storeInCache<T>(callback(), name);
} else {
let dataFromCache = localStorage.getItem(name);
try {
data = of(JSON.parse(dataFromCache));
} catch (err) {
console.error(
`Could not parse ${JSON.stringify(
dataFromCache
)}: ${err}. Fetching again data from callback function.`
);
data = storeInCache<T>(callback(), name);
}
}
return data;
}

View File

@ -1,6 +1,3 @@
import { Observable, switchMap, map } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';
export interface GithubRepo { export interface GithubRepo {
id: number; id: number;
node_id: string; node_id: string;
@ -48,9 +45,9 @@ export interface GithubRepo {
labels_url: string; labels_url: string;
releases_url: string; releases_url: string;
deployments_url: string; deployments_url: string;
created_at: Date; created_at: string;
updated_at: Date; updated_at: string;
pushed_at: Date; pushed_at: string;
git_url: string; git_url: string;
ssh_url: string; ssh_url: string;
clone_url: string; clone_url: string;
@ -107,33 +104,3 @@ export interface GithubError {
message: string; message: string;
documentation_url: string; documentation_url: string;
} }
export function getLatestRepositories(
user: string,
amount: number
): Observable<GithubRepo[]> {
return getRepositoriesOfUser(user).pipe(
map((repositories: GithubRepo[]) => {
return repositories
.sort(
(a: GithubRepo, b: GithubRepo) =>
+b.updated_at - +a.updated_at
)
.slice(0, amount);
})
);
}
export function getRepositoriesOfUser(user: string): Observable<GithubRepo[]> {
const fetchUrl = `https://api.github.com/users/${user}/repos`;
return fromFetch(fetchUrl).pipe(
switchMap((response: Response) => {
if (response.ok) {
return response.json();
} else {
console.error(`Error ${response.status}: ${JSON.stringify(response)}`);
return [];
}
}),
);
}

View File

@ -4,7 +4,7 @@ title: Projets
# Programmation # Programmation
## Projets GitHub les plus étoilés ## Projets GitHub les plus étoilés
<ClientOnly> <ClientOnly>
<LatestRepositories /> <ListRepositories sortBy='stars' user='phundrak' :limit='5' />
</ClientOnly> </ClientOnly>
## Derniers dépôts de code actifs sur GitHub ## Derniers dépôts de code actifs sur GitHub