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β
Parameter | Type | Required | Description |
---|---|---|---|
id | string | Yes | The unique identifier of the news article |
Request Bodyβ
Field | Type | Required | Description |
---|---|---|---|
action | string | Yes | Either "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β
-
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
-
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
-
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.
Related Endpointsβ
- Comments API - For news article comments
- News API - For news article management
- Notifications API - For like notifications
Changelogβ
v1.0.0 (Current)β
- Initial implementation with like/unlike functionality
- React 19 optimistic updates support
- Firebase Firestore integration
- Comprehensive error handling