add interactions to comments
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing

This commit is contained in:
Do-raa
2024-12-23 15:44:36 +01:00
parent 6d6d70295d
commit e24b3e1955
22 changed files with 3963 additions and 3410 deletions

54
lib/likes.ts Normal file
View File

@@ -0,0 +1,54 @@
/**
* Updates likes or dislikes for an article or comment dynamically.
* @param {string} type - 'article' or 'comment'.
* @param {string} action - 'like' or 'dislike'.
* @param {string} id - ID of the article or comment.
* @param {string} articleId - (Optional) ID of the parent article if updating a comment.
* @param {Array} articles - The articles array.
*/
export const updateLikeDislike = async ({ type, action, id, articleId = null, articles }) => {
try {
// Find the target item
let target;
if (type === 'article') {
target = articles.value.find((a) => a.id === id);
} else if (type === 'comment') {
const article = articles.value.find((a) => a.id === articleId);
if (article) {
target = article.comments.find((c) => c.id === id);
}
}
if (!target) {
console.error(`Target ${type} not found`);
return;
}
// Increment the likes or dislikes
if (action === 'like') {
target.likes += 1;
} else if (action === 'dislike') {
target.dislikes += 1;
} else {
console.error('Invalid action specified');
return;
}
// Determine API endpoint
const endpoint = type === 'article' ? `/api/articles/${id}` : `/api/comments/${id}`;
// Make the API call
await $fetch(endpoint, {
method: 'PUT',
body: {
[action === 'like' ? 'likes' : 'dislikes']: action === 'like' ? target.likes : target.dislikes,
...(type === 'comment' && { articleId }),
},
});
console.log(`${type} ${action} updated successfully`);
} catch (error) {
console.error(`Error updating ${type} ${action}:`, error);
}
};