clean code

This commit is contained in:
MuslemRahimi 2024-10-07 01:00:45 +02:00
parent a77e198907
commit bbadd8b9fc
9 changed files with 182 additions and 287 deletions

View File

@ -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));
};

View File

@ -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));
};

View File

@ -2,11 +2,73 @@ import { error, fail, redirect } from "@sveltejs/kit";
import { validateData } from "$lib/utils"; import { validateData } from "$lib/utils";
import { loginUserSchema, registerUserSchema } from "$lib/schemas"; 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 = { export const actions = {
login: async ({ request, locals }) => { login: async ({ request, locals }) => {
const { formData, errors } = await validateData( const { formData, errors } = await validateData(
await request.formData(), await request.formData(),
loginUserSchema, loginUserSchema
); );
if (errors) { if (errors) {
@ -40,7 +102,7 @@ export const actions = {
register: async ({ locals, request }) => { register: async ({ locals, request }) => {
const { formData, errors } = await validateData( const { formData, errors } = await validateData(
await request.formData(), await request.formData(),
registerUserSchema, registerUserSchema
); );
if (errors) { if (errors) {
@ -94,7 +156,7 @@ await locals.pb?.collection('users').update(
const redirectURL = `${url.origin}/oauth`; const redirectURL = `${url.origin}/oauth`;
const targetItem = authMethods.authProviders?.findIndex( const targetItem = authMethods.authProviders?.findIndex(
(item) => item?.name === providerSelected, (item) => item?.name === providerSelected
); );
//console.log("==================") //console.log("==================")
//console.log(authMethods.authProviders) //console.log(authMethods.authProviders)

View File

@ -22,9 +22,9 @@
let loading = true; let loading = true;
let moderators ; let moderators = data?.getModerators;
let communityStats; let communityStats = data?.getCommunityStats;
let discordData = []; let discordData = data?.getDiscordWidget
let posts = null; 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() { 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 LoginPopup;
let BottomNavigation; let BottomNavigation;
@ -187,11 +111,8 @@ let BottomNavigation;
onMount(async () => { onMount(async () => {
if (Object?.keys($cachedPosts)?.length === 0) { if (Object?.keys($cachedPosts)?.length === 0) {
// Only make API requests if cached posts are not available // Only make API requests if cached posts are not available
[communityStats, moderators, posts, discordData] = await Promise.all([ [posts] = await Promise.all([
getCommunityStats(),
getModerators(),
getPost(), getPost(),
getDiscordWidget(),
//getTickerMentioning(), //getTickerMentioning(),
]); ]);
@ -201,9 +122,6 @@ onMount(async () => {
else { else {
// Use cached data if available // Use cached data if available
posts = $cachedPosts?.posts; posts = $cachedPosts?.posts;
communityStats = getCache('', 'getCommunityStats');
moderators = getCache('', 'getModerators');
discordData = getCache('','getDiscordWidget');
//tickerMentioning = getCache('','getTickerMentioning'); //tickerMentioning = getCache('','getTickerMentioning');
} }

View File

@ -1,15 +1,16 @@
import { redirect, error } from "@sveltejs/kit"; import { redirect, error } from "@sveltejs/kit";
export const load = async ({ locals }) => { export const load = async ({ locals }) => {
if (!locals.pb.authStore.isValid) { const { pb, user } = locals;
if (!pb.authStore.isValid) {
redirect(303, "/login"); redirect(303, "/login");
} }
const getSubscriptionData = async () => { const getSubscriptionData = async () => {
const output = const output =
( (
await locals.pb.collection("payments").getFullList({ await pb.collection("payments").getFullList({
filter: `user="${locals.user.id}" `, filter: `user="${user.id}" `,
sort: "-created", sort: "-created",
}) })
)?.at(0)?.data?.data?.attributes ?? {}; )?.at(0)?.data?.data?.attributes ?? {};
@ -19,8 +20,46 @@ export const load = async ({ locals }) => {
return output; 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 { return {
getSubscriptionData: await getSubscriptionData(), getSubscriptionData: await getSubscriptionData(),
getModerators: await getModerators(),
getUserStats: await getUserStats(),
}; };
}; };

View File

@ -7,7 +7,7 @@
import { onMount, onDestroy } from 'svelte'; import { onMount, onDestroy } from 'svelte';
import {getImageURL, addDays } from '$lib/utils'; 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 toast from 'svelte-french-toast';
import InfiniteLoading from '$lib/components/InfiniteLoading.svelte'; import InfiniteLoading from '$lib/components/InfiniteLoading.svelte';
@ -22,8 +22,7 @@
let zodErrors = []; let zodErrors = [];
let moderators; let moderators = data?.getModerators;
let numberOfPosts = '-';
let loading = true; let loading = true;
let isLoaded = false; let isLoaded = false;
let errorAvatar; let errorAvatar;
@ -33,7 +32,7 @@
let errorPasswordConfirm = ''; let errorPasswordConfirm = '';
let subscriptionData = data?.getSubscriptionData; let subscriptionData = data?.getSubscriptionData;
let isClicked = false; let isClicked = false;
let userStats = {'numberOfPosts': 0, 'numberOfComments': 0} let userStats = data?.getUserStats ?? {'numberOfPosts': 0, 'numberOfComments': 0}
const showPreview = (event) => { const showPreview = (event) => {
const target = event.target; const target = event.target;
@ -329,70 +328,11 @@ 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) { function isModerator(data, moderators) {
return moderators?.some(moderator => data?.user?.id === moderator?.expand?.user?.id); 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[] = []; let posts: any[] = [];
@ -492,10 +432,8 @@ onMount(async () => {
window.scrollTo(0, 0); window.scrollTo(0, 0);
[posts, moderators, userStats] = await Promise.all([ [posts] = await Promise.all([
getPost(), getPost(),
getModerators(),
getUserStats(),
]); ]);
loading = false; loading = false;

View File

@ -3,7 +3,9 @@ import { validateData } from "$lib/utils";
import { loginUserSchema, registerUserSchema } from "$lib/schemas"; import { loginUserSchema, registerUserSchema } from "$lib/schemas";
export const load = async ({ locals, params }) => { 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"); redirect(303, "/community/profile");
} }
@ -11,8 +13,62 @@ export const load = async ({ locals, params }) => {
return params.userId; 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 { return {
userId: await userId(), userId: await userId(),
getModerators: await getModerators(),
getUserStats: await getUserStats(),
getUserData: await getUserData(),
}; };
}; };
@ -20,7 +76,7 @@ export const actions = {
login: async ({ request, locals }) => { login: async ({ request, locals }) => {
const { formData, errors } = await validateData( const { formData, errors } = await validateData(
await request.formData(), await request.formData(),
loginUserSchema, loginUserSchema
); );
if (errors) { if (errors) {
@ -54,7 +110,7 @@ export const actions = {
register: async ({ locals, request }) => { register: async ({ locals, request }) => {
const { formData, errors } = await validateData( const { formData, errors } = await validateData(
await request.formData(), await request.formData(),
registerUserSchema, registerUserSchema
); );
if (errors) { if (errors) {
@ -92,9 +148,7 @@ await locals.pb?.collection('users').update(
}, },
oauth2: async ({ url, locals, request, cookies }) => { oauth2: async ({ url, locals, request, cookies }) => {
const authMethods = await locals?.pb const authMethods = await pb?.collection("users")?.listAuthMethods();
?.collection("users")
?.listAuthMethods();
const data = await request?.formData(); const data = await request?.formData();
const providerSelected = data?.get("provider"); const providerSelected = data?.get("provider");
@ -108,7 +162,7 @@ await locals.pb?.collection('users').update(
const redirectURL = `${url.origin}/oauth`; const redirectURL = `${url.origin}/oauth`;
const targetItem = authMethods.authProviders?.findIndex( const targetItem = authMethods.authProviders?.findIndex(
(item) => item?.name === providerSelected, (item) => item?.name === providerSelected
); );
//console.log("==================") //console.log("==================")
//console.log(authMethods.authProviders) //console.log(authMethods.authProviders)

View File

@ -6,7 +6,7 @@
import { onMount} from 'svelte'; import { onMount} from 'svelte';
import {getImageURL } from '$lib/utils'; import {getImageURL } from '$lib/utils';
import {setCache, getCache, numberOfUnreadNotification } from '$lib/store'; import {numberOfUnreadNotification } from '$lib/store';
import InfiniteLoading from '$lib/components/InfiniteLoading.svelte'; import InfiniteLoading from '$lib/components/InfiniteLoading.svelte';
@ -15,13 +15,9 @@
export let form; export let form;
let userData = { let userData = data?.getUserData
"karma": 0,
"stockfinder": true,
"username": '-',
}
let userStats = {'numberOfPosts': 0, 'numberOfComments': 0} let userStats = data?.getUserStats ?? {'numberOfPosts': 0, 'numberOfComments': 0}
let moderators; let moderators;
let showTab = 'post' let showTab = 'post'
@ -40,22 +36,6 @@ let seenPostId = [];
let noPostMore = false; 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 } }) async function infiniteHandler({ detail: { loaded, complete } })
{ {
@ -84,62 +64,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) { function isModerator(moderators) {
return moderators?.some(moderator => data?.userId === moderator?.expand?.user?.id); return moderators?.some(moderator => data?.userId === moderator?.expand?.user?.id);
} }
@ -180,13 +104,10 @@ onMount(async () => {
window.scrollTo(0, 0); window.scrollTo(0, 0);
[posts, moderators, userData, userStats] = await Promise?.all([ [posts] = await Promise?.all([
getPost(), getPost(),
getModerators(),
getUserData(),
getUserStats(),
]); ]);
console.log(moderators)
if(!data?.userData) if(!data?.userData)
{ {
LoginPopup = (await import('$lib/components/LoginPopup.svelte')).default; LoginPopup = (await import('$lib/components/LoginPopup.svelte')).default;

View File

@ -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 brotliSize: true, // Enable Brotli compression
}, },