clean up api endpoints

This commit is contained in:
MuslemRahimi 2024-10-07 16:15:17 +02:00
parent bbadd8b9fc
commit 80ff3ce4cc
5 changed files with 95 additions and 129 deletions

View File

@ -1,18 +0,0 @@
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request, locals }) => {
const data = await request.json();
const { fastifyURL } = locals;
const response = await fetch(fastifyURL + "/get-all-comments", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const output = await response.json();
return new Response(JSON.stringify(output));
};

View File

@ -1,10 +1,10 @@
import { pb } from "$lib/pocketbase";
import { getCache, setCache } from "$lib/store";
export const load = async ({ parent }) => {
export const load = async () => {
const getAllBlogPost = async () => {
let output;
console.log(await parent());
// Get cached data for the specific tickerID
const cachedData = getCache("allBlogPost", "getAllBlogPost");
if (cachedData) {

View File

@ -2,11 +2,97 @@ import { error, fail, redirect } from "@sveltejs/kit";
import { validateData } from "$lib/utils";
import { loginUserSchema, registerUserSchema } from "$lib/schemas";
function listToTree(comments, parentProp = "reply") {
// Create id indexed comments dictionary
const commentsDict = {};
for (let comment of comments) {
commentsDict[comment.id] = {
...comment,
children: [],
};
}
// Build the tree
const tree = [];
for (const comment of comments) {
const parentId = comment[parentProp];
if (parentId) {
commentsDict[parentId].children.push(commentsDict[comment.id]);
} else {
tree.push(commentsDict[comment.id]);
}
}
return tree;
}
export const load = async ({ locals, params, fetch }) => {
const { pb } = locals;
async function getOnePost() {
// If the post is not found in the cache, fetch it from the endpoint
const postData = { postId: params.postId };
const response = await fetch("/api/get-one-post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(postData),
});
const result = await response.json();
// Assuming the result contains an 'items' array
return result?.items;
}
const getPostId = async () => {
return params.postId;
};
const getModerators = async () => {
let output;
try {
output = await pb.collection("moderators").getFullList({
expand: "user",
});
} catch (e) {
output = [];
}
return output;
};
const getAllComments = async () => {
let output;
try {
const result = await pb.collection("comments").getFullList({
filter: `post="${params.postId}"`,
expand: "user,alreadyVoted(comment)",
fields:
"*,expand.user,expand.alreadyVoted(comment).user,expand.alreadyVoted(comment).type",
sort: "-created",
});
output = listToTree(result);
} catch (e) {
output = [];
}
return output;
};
return {
getModerators: await getModerators(),
getAllComments: await getAllComments(),
getPostId: await getPostId(),
getOnePost: await getOnePost(),
};
};
export const actions = {
login: async ({ request, locals }) => {
const { formData, errors } = await validateData(
await request.formData(),
loginUserSchema,
loginUserSchema
);
if (errors) {
@ -40,7 +126,7 @@ export const actions = {
register: async ({ locals, request }) => {
const { formData, errors } = await validateData(
await request.formData(),
registerUserSchema,
registerUserSchema
);
if (errors) {
@ -94,7 +180,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)

View File

@ -18,6 +18,9 @@
export let data;
export let form;
let moderators = data?.getModerators;
let comments = data?.getAllComments;
let numberOfComments = 0;
let post = data?.getOnePost;
let isScrolled = false;
@ -189,68 +192,12 @@
};
let numberOfComments = 0;
let comments = [];
//let replyComments = data?.allReplyComments?.items.reverse() || [];
let moderators;
let videoId = null;
let loadTextEditor = false;
async function getAllComments()
{
const postData = {'postId': data?.getPostId};
// make the GET request to the endpoint
const response = await fetch('/api/get-all-comments', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData),
});
const output = (await response.json())?.items;
return output;
};
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(userId) {
return moderators?.some(moderator => userId === moderator?.user);
@ -293,12 +240,7 @@
{
LoginPopup = (await import('$lib/components/LoginPopup.svelte')).default;
}
[moderators, comments] = await Promise.all([
getModerators(),
getAllComments(),
]);
numberOfComments = countAllComments(comments) || 0;
if (post?.postType === 'link') {

View File

@ -1,44 +0,0 @@
import { cachedPosts } from "$lib/store";
import { get } from "svelte/store";
export const load = async ({ params, fetch }) => {
async function getOnePost() {
// Get the current value of cachedPosts
const cachedValue = get(cachedPosts);
// Try to find the post in the cached value
const output =
cachedValue?.posts?.find((item) => item?.id === params.postId) ?? {};
// If the post is found in the cache, return it
if (Object?.keys(output)?.length !== 0) {
return output;
}
// If the post is not found in the cache, fetch it from the endpoint
const postData = { postId: params.postId };
const response = await fetch("/api/get-one-post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(postData),
});
const result = await response.json();
// Assuming the result contains an 'items' array
return result?.items;
}
const getPostId = async () => {
return params.postId;
};
return {
getPostId: await getPostId(),
getOnePost: await getOnePost(),
};
};