From bbadd8b9fc402095fe9e440239cbc81efd2212ca Mon Sep 17 00:00:00 2001 From: MuslemRahimi Date: Mon, 7 Oct 2024 01:00:45 +0200 Subject: [PATCH] clean code --- src/routes/api/get-community-stats/+server.ts | 16 ---- src/routes/api/get-moderators/+server.ts | 16 ---- src/routes/community/+page.server.ts | 68 +++++++++++++- src/routes/community/+page.svelte | 90 +----------------- src/routes/community/profile/+page.server.ts | 45 ++++++++- src/routes/community/profile/+page.svelte | 70 +------------- .../community/user/[userId]/+page.server.ts | 68 ++++++++++++-- .../community/user/[userId]/+page.svelte | 91 ++----------------- vite.config.js | 5 - 9 files changed, 182 insertions(+), 287 deletions(-) delete mode 100644 src/routes/api/get-community-stats/+server.ts delete mode 100644 src/routes/api/get-moderators/+server.ts diff --git a/src/routes/api/get-community-stats/+server.ts b/src/routes/api/get-community-stats/+server.ts deleted file mode 100644 index a25c0e35..00000000 --- a/src/routes/api/get-community-stats/+server.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { RequestHandler } from "./$types"; - -export const GET: RequestHandler = async ({ locals }) => { - const { fastifyURL } = locals; - - const response = await fetch(fastifyURL + "/get-community-stats", { - method: "GET", - headers: { - "Content-Type": "application/json", - }, - }); - - const output = await response.json(); - - return new Response(JSON.stringify(output)); -}; diff --git a/src/routes/api/get-moderators/+server.ts b/src/routes/api/get-moderators/+server.ts deleted file mode 100644 index 3a9560ca..00000000 --- a/src/routes/api/get-moderators/+server.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { RequestHandler } from "./$types"; - -export const GET: RequestHandler = async ({ locals }) => { - const { fastifyURL } = locals; - - const response = await fetch(fastifyURL + "/get-moderators", { - method: "GET", - headers: { - "Content-Type": "application/json", - }, - }); - - const output = await response.json(); - - return new Response(JSON.stringify(output)); -}; diff --git a/src/routes/community/+page.server.ts b/src/routes/community/+page.server.ts index f26ed856..b2a4754b 100644 --- a/src/routes/community/+page.server.ts +++ b/src/routes/community/+page.server.ts @@ -2,11 +2,73 @@ import { error, fail, redirect } from "@sveltejs/kit"; import { validateData } from "$lib/utils"; import { loginUserSchema, registerUserSchema } from "$lib/schemas"; +export const load = async ({ locals, setHeaders }) => { + const { pb } = locals; + + const getDiscordWidget = async () => { + // make the POST request to the endpoint + const response = await fetch( + "https://discord.com/api/guilds/1165618982133436436/widget.json", + { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + } + ); + + const output = await response.json(); + + return output; + }; + + const getCommunityStats = async () => { + let output; + let totalUsers = 0; + let totalPosts = 0; + let totalComments = 0; + + try { + totalUsers = (await pb.collection("users").getList(1, 1))?.totalItems; + totalPosts = (await pb.collection("posts").getList(1, 1))?.totalItems; + totalComments = (await pb.collection("comments").getList(1, 1)) + ?.totalItems; + + output = { totalUsers, totalPosts, totalComments }; + } catch (e) { + console.error(e); + output = { totalUsers, totalPosts, totalComments }; + } + + return output; + }; + + const getModerators = async () => { + let output; + try { + output = await pb.collection("moderators").getFullList({ + expand: "user", + }); + } catch (e) { + output = []; + } + return output; + }; + + setHeaders({ "cache-control": "public, max-age=3000" }); + // Make sure to return a promise + return { + getDiscordWidget: await getDiscordWidget(), + getCommunityStats: await getCommunityStats(), + getModerators: await getModerators(), + }; +}; + export const actions = { login: async ({ request, locals }) => { const { formData, errors } = await validateData( await request.formData(), - loginUserSchema, + loginUserSchema ); if (errors) { @@ -40,7 +102,7 @@ export const actions = { register: async ({ locals, request }) => { const { formData, errors } = await validateData( await request.formData(), - registerUserSchema, + registerUserSchema ); if (errors) { @@ -94,7 +156,7 @@ await locals.pb?.collection('users').update( const redirectURL = `${url.origin}/oauth`; const targetItem = authMethods.authProviders?.findIndex( - (item) => item?.name === providerSelected, + (item) => item?.name === providerSelected ); //console.log("==================") //console.log(authMethods.authProviders) diff --git a/src/routes/community/+page.svelte b/src/routes/community/+page.svelte index b16bddcd..9833d7b5 100644 --- a/src/routes/community/+page.svelte +++ b/src/routes/community/+page.svelte @@ -22,9 +22,9 @@ let loading = true; - let moderators ; - let communityStats; - let discordData = []; + let moderators = data?.getModerators; + let communityStats = data?.getCommunityStats; + let discordData = data?.getDiscordWidget let posts = null; @@ -63,58 +63,6 @@ async function infiniteHandler({ detail: { loaded, complete } }) } -1 - -const getModerators = async () => { - let output; - - // Get cached data for the specific tickerID - const cachedData = getCache('', 'getModerators'); - if (cachedData) { - output = cachedData; - } else { - - const response = await fetch('/api/get-moderators', { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - }, - }); - - output = (await response.json())?.items; - - setCache('', output, 'getModerators'); - } - - return output; - }; - - - -const getCommunityStats = async () => { - let output; - // Get cached data for the specific tickerID - const cachedData = getCache('', 'getCommunityStats'); - if (cachedData) { - output = cachedData; - } else { - - const response = await fetch('/api/get-community-stats', { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - }, - }); - - output = (await response.json())?.items; - - - setCache('', output, 'getCommunityStats'); - } - - return output; -}; - async function getPost() { @@ -156,30 +104,6 @@ async function getPost() { } -const getDiscordWidget = async () => { - let output; - // Get cached data for the specific tickerID - const cachedData = getCache('', 'getDiscordWidget'); - if (cachedData) { - output = cachedData; - } else { - - // make the POST request to the endpoint - const response = await fetch('https://discord.com/api/guilds/1165618982133436436/widget.json', { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - }, - }); - - output = await response.json(); - setCache('', output, 'getDiscordWidget'); - } - - return output; -}; - - let LoginPopup; let BottomNavigation; @@ -187,11 +111,8 @@ let BottomNavigation; onMount(async () => { if (Object?.keys($cachedPosts)?.length === 0) { // Only make API requests if cached posts are not available - [communityStats, moderators, posts, discordData] = await Promise.all([ - getCommunityStats(), - getModerators(), + [posts] = await Promise.all([ getPost(), - getDiscordWidget(), //getTickerMentioning(), ]); @@ -201,9 +122,6 @@ onMount(async () => { else { // Use cached data if available posts = $cachedPosts?.posts; - communityStats = getCache('', 'getCommunityStats'); - moderators = getCache('', 'getModerators'); - discordData = getCache('','getDiscordWidget'); //tickerMentioning = getCache('','getTickerMentioning'); } diff --git a/src/routes/community/profile/+page.server.ts b/src/routes/community/profile/+page.server.ts index 474dc6f0..66a19211 100644 --- a/src/routes/community/profile/+page.server.ts +++ b/src/routes/community/profile/+page.server.ts @@ -1,15 +1,16 @@ import { redirect, error } from "@sveltejs/kit"; export const load = async ({ locals }) => { - if (!locals.pb.authStore.isValid) { + const { pb, user } = locals; + if (!pb.authStore.isValid) { redirect(303, "/login"); } const getSubscriptionData = async () => { const output = ( - await locals.pb.collection("payments").getFullList({ - filter: `user="${locals.user.id}" `, + await pb.collection("payments").getFullList({ + filter: `user="${user.id}" `, sort: "-created", }) )?.at(0)?.data?.data?.attributes ?? {}; @@ -19,8 +20,46 @@ export const load = async ({ locals }) => { return output; }; + const getModerators = async () => { + let output; + try { + output = await pb.collection("moderators").getFullList({ + expand: "user", + }); + } catch (e) { + output = []; + } + return output; + }; + + const getUserStats = async () => { + let output; + + try { + const getNumberOfPosts = await pb.collection("posts").getList(1, 1, { + filter: `user="${user?.id}"`, + }); + const numberOfPosts = getNumberOfPosts?.totalItems; + + const getNumberOfComments = await pb + .collection("comments") + .getList(1, 1, { + filter: `user="${user?.id}"`, + }); + const numberOfComments = getNumberOfComments?.totalItems; + + output = { numberOfPosts, numberOfComments }; + } catch (e) { + output = { numberOfPosts: 0, numberOfComments: 0 }; + } + + return output; + }; + return { getSubscriptionData: await getSubscriptionData(), + getModerators: await getModerators(), + getUserStats: await getUserStats(), }; }; diff --git a/src/routes/community/profile/+page.svelte b/src/routes/community/profile/+page.svelte index aefa7673..b9c6b10c 100644 --- a/src/routes/community/profile/+page.svelte +++ b/src/routes/community/profile/+page.svelte @@ -7,7 +7,7 @@ import { onMount, onDestroy } from 'svelte'; import {getImageURL, addDays } from '$lib/utils'; - import {setCache, getCache, newAvatar, numberOfUnreadNotification, postIdDeleted } from '$lib/store'; + import {newAvatar, numberOfUnreadNotification, postIdDeleted } from '$lib/store'; import toast from 'svelte-french-toast'; import InfiniteLoading from '$lib/components/InfiniteLoading.svelte'; @@ -22,8 +22,7 @@ let zodErrors = []; - let moderators; - let numberOfPosts = '-'; + let moderators = data?.getModerators; let loading = true; let isLoaded = false; let errorAvatar; @@ -33,7 +32,7 @@ let errorPasswordConfirm = ''; let subscriptionData = data?.getSubscriptionData; let isClicked = false; - let userStats = {'numberOfPosts': 0, 'numberOfComments': 0} + let userStats = data?.getUserStats ?? {'numberOfPosts': 0, 'numberOfComments': 0} const showPreview = (event) => { const target = event.target; @@ -328,71 +327,12 @@ async function updatePassword(event) { } - -const getModerators = async () => { - let output; - - // Get cached data for the specific tickerID - const cachedData = getCache('', 'getModerators'); - if (cachedData) { - output = cachedData; - } else { - - // make the POST request to the endpoint - const response = await fetch('/api/get-moderators', { - method: 'GET', - headers: { - "Content-Type": "application/json" - }, - }); - - output = (await response.json())?.items; - - setCache('', output, 'getModerators'); - } - - return output; - }; - - function isModerator(data, moderators) { return moderators?.some(moderator => data?.user?.id === moderator?.expand?.user?.id); } -const getUserStats = async () => { - let output; - - // Get cached data for the specific tickerID - const cachedData = getCache(data?.user?.id, 'getUserStats'); - if (cachedData) { - output = cachedData; - } else { - - const postData = {'userId': data?.user?.id, 'path': 'get-user-stats'}; - - // make the POST request to the endpoint - const response = await fetch('/api/fastify-post-data', { - method: 'POST', - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify(postData) - }); - - output = (await response.json())?.items; - - - setCache(data?.user?.id, output, 'getUserStats'); - } - - return output -}; - - - - let posts: any[] = []; @@ -492,10 +432,8 @@ onMount(async () => { window.scrollTo(0, 0); - [posts, moderators, userStats] = await Promise.all([ + [posts] = await Promise.all([ getPost(), - getModerators(), - getUserStats(), ]); loading = false; diff --git a/src/routes/community/user/[userId]/+page.server.ts b/src/routes/community/user/[userId]/+page.server.ts index 6abfad41..3d172cb2 100644 --- a/src/routes/community/user/[userId]/+page.server.ts +++ b/src/routes/community/user/[userId]/+page.server.ts @@ -3,7 +3,9 @@ import { validateData } from "$lib/utils"; import { loginUserSchema, registerUserSchema } from "$lib/schemas"; export const load = async ({ locals, params }) => { - if (params.userId === locals?.user?.id) { + const { pb, user } = locals; + + if (params.userId === user?.id) { redirect(303, "/community/profile"); } @@ -11,8 +13,62 @@ export const load = async ({ locals, params }) => { return params.userId; }; + const getModerators = async () => { + let output; + try { + output = await pb.collection("moderators").getFullList({ + expand: "user", + }); + } catch (e) { + output = []; + } + return output; + }; + + const getUserStats = async () => { + let output; + + try { + const getNumberOfPosts = await pb.collection("posts").getList(1, 1, { + filter: `user="${params.userId}"`, + }); + const numberOfPosts = getNumberOfPosts?.totalItems; + + const getNumberOfComments = await pb + .collection("comments") + .getList(1, 1, { + filter: `user="${params.userId}"`, + }); + const numberOfComments = getNumberOfComments?.totalItems; + + output = { numberOfPosts, numberOfComments }; + } catch (e) { + output = { numberOfPosts: 0, numberOfComments: 0 }; + } + + return output; + }; + + const getUserData = async () => { + let output; + + try { + output = await pb.collection("users").getOne(params?.userId); + } catch (e) { + output = { + karma: 0, + username: "-", + }; + } + + return output; + }; + return { userId: await userId(), + getModerators: await getModerators(), + getUserStats: await getUserStats(), + getUserData: await getUserData(), }; }; @@ -20,7 +76,7 @@ export const actions = { login: async ({ request, locals }) => { const { formData, errors } = await validateData( await request.formData(), - loginUserSchema, + loginUserSchema ); if (errors) { @@ -54,7 +110,7 @@ export const actions = { register: async ({ locals, request }) => { const { formData, errors } = await validateData( await request.formData(), - registerUserSchema, + registerUserSchema ); if (errors) { @@ -92,9 +148,7 @@ await locals.pb?.collection('users').update( }, oauth2: async ({ url, locals, request, cookies }) => { - const authMethods = await locals?.pb - ?.collection("users") - ?.listAuthMethods(); + const authMethods = await pb?.collection("users")?.listAuthMethods(); const data = await request?.formData(); const providerSelected = data?.get("provider"); @@ -108,7 +162,7 @@ await locals.pb?.collection('users').update( const redirectURL = `${url.origin}/oauth`; const targetItem = authMethods.authProviders?.findIndex( - (item) => item?.name === providerSelected, + (item) => item?.name === providerSelected ); //console.log("==================") //console.log(authMethods.authProviders) diff --git a/src/routes/community/user/[userId]/+page.svelte b/src/routes/community/user/[userId]/+page.svelte index e6e9abd1..4e35b626 100644 --- a/src/routes/community/user/[userId]/+page.svelte +++ b/src/routes/community/user/[userId]/+page.svelte @@ -6,7 +6,7 @@ import { onMount} from 'svelte'; import {getImageURL } from '$lib/utils'; - import {setCache, getCache, numberOfUnreadNotification } from '$lib/store'; + import {numberOfUnreadNotification } from '$lib/store'; import InfiniteLoading from '$lib/components/InfiniteLoading.svelte'; @@ -15,13 +15,9 @@ export let form; - let userData = { - "karma": 0, - "stockfinder": true, - "username": '-', -} + let userData = data?.getUserData -let userStats = {'numberOfPosts': 0, 'numberOfComments': 0} +let userStats = data?.getUserStats ?? {'numberOfPosts': 0, 'numberOfComments': 0} let moderators; let showTab = 'post' @@ -40,22 +36,6 @@ let seenPostId = []; let noPostMore = false; -const getUserData = async() => { - - const postData = {'userId': data?.userId, 'path': 'get-user-data'}; - - const response = await fetch('/api/fastify-post-data', { - method: 'POST', - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify(postData) - }); - - const output = (await response.json())?.items; - - return output; -}; async function infiniteHandler({ detail: { loaded, complete } }) { @@ -83,62 +63,6 @@ async function infiniteHandler({ detail: { loaded, complete } }) } - -const getUserStats = async () => { - let output; - - // Get cached data for the specific tickerID - const cachedData = getCache(data?.userId, 'getUserStats'); - if (cachedData) { - output = cachedData; - } else { - - const postData = {'userId': data?.userId, 'path': 'get-user-stats'}; - - // make the POST request to the endpoint - const response = await fetch('/api/fastify-post-data', { - method: 'POST', - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify(postData) - }); - - output = (await response.json())?.items; - - - setCache(data?.userId, output, 'getUserStats'); - } - - return output -}; - - -const getModerators = async () => { - let output; - - // Get cached data for the specific tickerID - const cachedData = getCache('', 'getModerators'); - if (cachedData) { - output = cachedData; - } else { - - const response = await fetch('/api/get-moderators', { - method: 'GET', - headers: { - "Content-Type": "application/json" - }, - }); - - output = (await response.json())?.items; - - setCache('', output, 'getModerators'); - } - - return output; -}; - - function isModerator(moderators) { return moderators?.some(moderator => data?.userId === moderator?.expand?.user?.id); @@ -180,14 +104,11 @@ onMount(async () => { window.scrollTo(0, 0); - [posts, moderators, userData, userStats] = await Promise?.all([ + [posts] = await Promise?.all([ getPost(), - getModerators(), - getUserData(), - getUserStats(), ]); - console.log(moderators) - if(!data?.userData) + + if(!data?.userData) { LoginPopup = (await import('$lib/components/LoginPopup.svelte')).default; } diff --git a/vite.config.js b/vite.config.js index 4c21e149..a7e11d71 100644 --- a/vite.config.js +++ b/vite.config.js @@ -28,11 +28,6 @@ const config = { } }, }, - // Add dynamicRequireTargets to handle specific dynamic imports - dynamicRequireTargets: [ - "node_modules/sharp/**/*", - // add other paths if necessary - ], }, brotliSize: true, // Enable Brotli compression },