Bruno Predot

Factorisation en incluant les guards clauses et ternaires.

... ... @@ -38,20 +38,13 @@ async function fetchMovies(page: number) {
try {
isLoadingMore.value = true;
const data = await fetchPopularMovies(page);
// Save in Movie model.
if (isInitialLoading.value) {
// First fetch, erase old data before save.
useRepo(Movie).fresh(data.results);
}
else {
// Add to store collection.
useRepo(Movie).save(data.results);
}
// Save in Movie model. If first fetch, erase old data before save or, add to store collection.
isInitialLoading.value ? useRepo(Movie).fresh(data.results) : useRepo(Movie).save(data.results);
totalPages.value = data.total_pages;
currentPage.value = page;
}
catch (error) {
console.error("Error fetching popular movies:", error);
throw new Error(`Error fetching popular movies: ${error}`);
}
finally {
isInitialLoading.value = false;
... ... @@ -72,24 +65,16 @@ async function search(query: string, page: number) {
}
try {
isLoadingMore.value = true;
if (page === 1) {
isInitialLoading.value = true;
}
if (page === 1) isInitialLoading.value = true;
const data = await searchMovies(query, page);
// Save in Movie model.
if (isInitialLoading.value) {
// First fetch, erase old data before save.
useRepo(Movie).fresh(data.results);
}
else {
// Add to store collection.
useRepo(Movie).save(data.results);
}
// Save in Movie model. If first fetch, erase old data before save or, add to store collection.
isInitialLoading.value ? useRepo(Movie).fresh(data.results) : useRepo(Movie).save(data.results);
totalPages.value = data.total_pages;
currentPage.value = page;
}
catch (error) {
console.error("Error searching movies:", error);
throw new Error(`Error searching movies: ${error}`);
}
finally {
isInitialLoading.value = false;
... ... @@ -101,16 +86,8 @@ function createIntersectionObserver() {
return new IntersectionObserver(
(entries) => {
const [entry] = entries;
if (entry.isIntersecting && !isLoadingMore.value && currentPage.value < totalPages.value) {
if (searchQuery.value) {
// Continue searching query if already active.
search(searchQuery.value, currentPage.value + 1);
}
else {
// Continue fetching popular movies.
fetchMovies(currentPage.value + 1);
}
}
// Continue searching query if already active or, continue fetching popular movies.
if (entry.isIntersecting && !isLoadingMore.value && currentPage.value < totalPages.value) searchQuery.value ? search(searchQuery.value, currentPage.value + 1) : fetchMovies(currentPage.value + 1);
},
{ threshold: 1.0 },
);
... ... @@ -137,21 +114,15 @@ onMounted(() => {
fetchMovies(1);
// Création et stockage dans la ref de l'instance IntersectionObserver.
observer.value = createIntersectionObserver();
if (loadMoreTrigger.value) {
// Début d'observation de la div pour le défilement infini.
observer.value.observe(loadMoreTrigger.value);
}
// Début d'observation de la div pour le défilement infini.
if (loadMoreTrigger.value) observer.value.observe(loadMoreTrigger.value);
if (loadMoreTrigger.value) {
observer.value.observe(loadMoreTrigger.value);
}
if (loadMoreTrigger.value) observer.value.observe(loadMoreTrigger.value);
});
onBeforeUnmount(() => {
// Disconnect the observer when the component is unmounted.
if (observer.value) {
observer.value.disconnect();
}
if (observer.value) observer.value.disconnect();
});
// #endregion
</script>
... ...
... ... @@ -13,9 +13,7 @@ defineProps<{
* @param count
*/
function formatVoteCount(count: number) {
if (count >= 1000) {
return `${(count / 1000).toFixed(1)}k votes`;
}
if (count >= 1000) return `${(count / 1000).toFixed(1)}k votes`;
return `${count} votes`;
}
// #endregion
... ...
... ... @@ -117,9 +117,7 @@ function handleMessageEvent(event: string) {
@click="
async () => {
const validForm = await v$.$validate();
if (validForm) {
submitComment();
}
if (validForm) submitComment();
}
"
>
... ...
... ... @@ -69,9 +69,7 @@ watch(content, (newValue) => {
watch(
() => props.modelValue,
(newValue) => {
if (newValue !== content.value) {
content.value = newValue;
}
if (newValue !== content.value) content.value = newValue;
},
);
// #endregion
... ...
... ... @@ -12,15 +12,11 @@ export function useTMDB() {
const fetchPopularMovies = async (page: number) => {
try {
const response = await fetch(`${apiUrl}/movie/popular?api_key=${apiKey}&language=fr-FR&page=${page}`);
if (!response.ok) {
console.error("An error occurred when fetching popular movies:");
}
else {
return await response.json();
}
if (!response.ok) throw new Error("An error occurred when fetching popular movies");
return await response.json();
}
catch (error) {
console.error("Error fetching popular movies:", error);
throw new Error(`Error fetching popular movies: ${error}`);
}
};
... ... @@ -34,15 +30,11 @@ export function useTMDB() {
const response = await fetch(
`${apiUrl}/search/movie?api_key=${apiKey}&language=fr-FR&query=${encodeURIComponent(query)}&page=${page}`,
);
if (!response.ok) {
console.error("An error occurred when searching movies:");
}
else {
return await response.json();
}
if (!response.ok) throw new Error("An error occurred when searching movies");
return await response.json();
}
catch (error) {
console.error("Error searching movies:", error);
throw new Error(`Error searching movies: ${error}`);
}
};
... ... @@ -53,15 +45,11 @@ export function useTMDB() {
const fetchMovieDetails = async (id: number | string) => {
try {
const response = await fetch(`${apiUrl}/movie/${id}?api_key=${apiKey}&language=fr-FR`);
if (!response.ok) {
console.error("An error occurred when fetching movie details:");
}
else {
return await response.json();
}
if (!response.ok) throw new Error("An error occurred when fetching movie details");
return await response.json();
}
catch (error) {
console.error("Error fetching details:", error);
throw new Error(`Error fetching details: ${error}`);
}
};
... ... @@ -71,15 +59,11 @@ export function useTMDB() {
const fetchMovieCredits = async (id: number | string) => {
try {
const response = await fetch(`${apiUrl}/movie/${id}/credits?api_key=${apiKey}&language=fr-FR`);
if (!response.ok) {
console.error("An error occurred when fetching movie credits:");
}
else {
return await response.json();
}
if (!response.ok) throw new Error("An error occurred when fetching movie credits");
return await response.json();
}
catch (error) {
console.error("Error fetching movie credits:", error);
throw new Error(`Error fetching movie credits: ${error}`);
}
};
... ...
import antfu from "@antfu/eslint-config";
export default antfu({
// Type of the project. 'lib' for libraries, the default is 'app'
type: "app",
// `.eslintignore` is no longer supported in Flat config, use `ignores` instead.
ignores: [
"**/fixtures",
"**/.cache",
"**/.data",
"**/.gitignore",
"**/.env",
"**/.env.dist",
"**/.output",
"**/.nitro",
"**/.nuxt",
"**/assets",
"**/dist",
"**/logs",
"**/node_modules",
"**/public",
"**/server",
],
// Disable jsonc and yaml support.
jsonc: false,
markdown: false,
// personnal rules.
rules: {
"antfu/if-newline": 0,
"antfu/curly": 0,
},
// Enable stylistic formatting rules
// Enable stylistic formatting rules.
// stylistic: true,
// Or customize the stylistic rules
// Or customize the stylistic rules.
stylistic: {
indent: 2, // 4, or 'tab'
semi: true,
stylistic: true,
quotes: "double", // 'single' or 'double'
quotes: "double", // 'single' or 'double'.
},
// Type of the project. 'lib' for libraries, the default is 'app'.
type: "app",
// TypeScript and Vue are autodetected, you can also explicitly enable them:
typescript: true,
vue: true,
// Disable jsonc and yaml support
jsonc: false,
markdown: false,
yaml: false,
// `.eslintignore` is no longer supported in Flat config, use `ignores` instead
ignores: [
"**/fixtures",
"**/.cache",
"**/.data",
"**/.gitignore",
"**/.env",
"**/.env.dist",
"**/.output",
"**/.nitro",
"**/.nuxt",
"**/assets",
"**/dist",
"**/logs",
"**/node_modules",
"**/public",
"**/server",
],
});
// Ancienne config eslint.
// Last eslint config.
// import withNuxt from "./.nuxt/eslint.config.mjs";
// import js from "@eslint/js";
// import eslintPluginVue from "eslint-plugin-vue";
... ...
... ... @@ -27,47 +27,28 @@ const isSubmitting = ref(false);
// #region --Computed--.
const movieId = computed(() => {
if (currentRoute.value.params.id) {
if (typeof currentRoute.value.params.id === "string") {
if (typeof Number(+currentRoute.value.params.id) === "number") {
return +currentRoute.value.params.id as number;
}
else {
return currentRoute.value.params.id as string;
}
}
else {
return null;
}
}
else {
return null;
}
if (!currentRoute.value.params.id) return null;
if (typeof currentRoute.value.params.id !== "string") return null;
if (typeof Number(+currentRoute.value.params.id) === "number") return +currentRoute.value.params.id as number;
return currentRoute.value.params.id as string;
});
const movie = computed(() => {
if (unref(movieId)) {
return useRepo(Movie)
.query()
.where("id", movieId.value as WhereSecondaryClosure<never> | null | undefined)
.withAll()
.first() as unknown as MovieInterface;
}
else {
return null;
}
if (!unref(movieId)) return null;
return useRepo(Movie)
.query()
.where("id", movieId.value as WhereSecondaryClosure<never> | null | undefined)
.withAll()
.first() as unknown as MovieInterface;
});
/**
* Computed property for director
*/
const director = computed(() => {
if (unref(movie)?.credit?.crew) {
return movie.value?.credit.crew.find(person => person.job === "Director");
}
else {
return null;
}
if (!unref(movie)?.credit?.crew) return null;
return movie.value?.credit.crew.find(person => person.job === "Director");
});
/**
... ... @@ -98,7 +79,7 @@ async function fetchDetails(id: number | string) {
useRepo(Movie).save(data);
}
catch (error) {
console.error("Error fetching movie details:", error);
throw new Error(`Error fetching movie details: ${error}`);
}
finally {
isLoading.value = false;
... ... @@ -110,8 +91,7 @@ async function fetchDetails(id: number | string) {
* @param minutes
*/
function formatRuntime(minutes: number) {
if (!minutes)
return "Durée inconnue";
if (!minutes) return "Durée inconnue";
// Find nb hours.
const hours = Math.floor(minutes / 60);
// Find last minutes.
... ... @@ -128,7 +108,7 @@ async function fetchCredits(id: number | string) {
useRepo(Credit).save(data);
}
catch (error) {
console.error("Error fetching movie credits:", error);
throw new Error(`Error fetching movie credits: ${error}`);
}
}
... ...