add interactions to comments
This commit is contained in:
54
lib/likes.ts
Normal file
54
lib/likes.ts
Normal 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);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user