Skip to main content

News Likes API

Overview​

The News Likes API allows users to like and unlike news articles, providing engagement functionality for the Ring Platform's news system.

Endpoint​

POST /api/news/[id]/like

Authentication​

Required: Yes - User must be authenticated via NextAuth session

Parameters​

Path Parameters​

ParameterTypeRequiredDescription
idstringYesThe unique identifier of the news article

Request Body​

FieldTypeRequiredDescription
actionstringYesEither "like" or "unlike"

Request Example​

curl -X POST https://ring.ck.ua/api/news/news123/like \
-H "Content-Type: application/json" \
-H "Cookie: next-auth.session-token=..." \
-d '{
"action": "like"
}'

Response Format​

Success Response (200 OK)​

{
"success": true,
"message": "Article liked successfully",
"data": {
"liked": true,
"totalLikes": 15
}
}

Unlike Success Response (200 OK)​

{
"success": true,
"message": "Article unliked successfully",
"data": {
"liked": false,
"totalLikes": 14
}
}

Error Responses​

401 Unauthorized​

{
"success": false,
"error": "Authentication required"
}

400 Bad Request​

{
"success": false,
"error": "Invalid action. Must be 'like' or 'unlike'"
}

404 Not Found​

{
"success": false,
"error": "News article not found"
}

500 Internal Server Error​

{
"success": false,
"error": "Failed to update like status"
}

Implementation Details​

Database Structure​

The likes are stored in Firebase Firestore with the following structure:

// Collection: news_likes
interface NewsLike {
id: string; // Auto-generated document ID
userId: string; // ID of the user who liked
targetId: string; // ID of the news article
targetType: 'news'; // Always 'news' for this endpoint
createdAt: Timestamp; // When the like was created
}

// Collection: news (updated with like count)
interface NewsArticle {
id: string;
// ... other fields
likeCount: number; // Total number of likes
updatedAt: Timestamp;
}

Business Logic​

  1. Like Action:

    • Check if user already liked the article
    • If not liked: Create like record and increment article's likeCount
    • If already liked: Return current status without changes
  2. Unlike Action:

    • Check if user has liked the article
    • If liked: Remove like record and decrement article's likeCount
    • If not liked: Return current status without changes
  3. Atomic Operations:

    • Uses Firebase transactions to ensure data consistency
    • Prevents race conditions when multiple users like simultaneously

Frontend Integration​

React 19 with useOptimistic​

import { useOptimistic } from 'react';
import { likeNews } from '@/app/actions/likes';

function NewsLikeButton({ newsId, initialLiked, initialCount }) {
const [optimisticState, addOptimistic] = useOptimistic(
{ liked: initialLiked, count: initialCount },
(state, action) => ({
liked: action === 'like' ? true : false,
count: action === 'like' ? state.count + 1 : state.count - 1
})
);

async function handleLike() {
const action = optimisticState.liked ? 'unlike' : 'like';
addOptimistic(action);

await likeNews('news', newsId, action);
}

return (
<button onClick={handleLike}>
{optimisticState.liked ? '❀️' : '🀍'} {optimisticState.count}
</button>
);
}

Server Action Integration​

// app/actions/likes.ts
export async function likeNews(
targetType: 'news',
targetId: string,
action: 'like' | 'unlike'
) {
const response = await fetch(`/api/news/${targetId}/like`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action })
});

return response.json();
}

Security Considerations​

  • Authentication: All requests require valid NextAuth session
  • Authorization: Users can only manage their own likes
  • Rate Limiting: Consider implementing rate limiting for like/unlike actions
  • Data Validation: All inputs are validated before processing
  • SQL Injection Prevention: Uses parameterized queries via Firebase SDK

Error Handling​

The API includes comprehensive error handling:

  • Input validation for required fields and valid actions
  • Authentication verification
  • Database operation error handling
  • Detailed error messages for debugging
  • Consistent error response format

Testing​

See the News Likes Testing Notebook for interactive testing examples and comprehensive test scenarios.

Changelog​

v1.0.0 (Current)​

  • Initial implementation with like/unlike functionality
  • React 19 optimistic updates support
  • Firebase Firestore integration
  • Comprehensive error handling