Back to API Reference

User Favorites API

Manage user's favorite chess openings with add/remove functionality and paginated retrieval.

Authentication Required

All endpoints in this API require valid user authentication. Unauthenticated requests will receive 401 Unauthorized.

POST
/api/user/favorites

Adds or removes an opening from the user's favorites list.

Request Body

{
  "openingId": "string (required)",
  "action": "string (required, enum: ['add', 'remove'])"
}

Example Request

// Add to favorites
const response = await fetch('/api/user/favorites', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    openingId: 'clk9x8d4q0001vq2o6q7q8r9s',
    action: 'add'
  })
});

// Remove from favorites
const response = await fetch('/api/user/favorites', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    openingId: 'clk9x8d4q0001vq2o6q7q8r9s',
    action: 'remove'
  })
});

Responses

200 OK - Added to Favorites
{
  "favorite": {
    "id": "string",
    "userId": "string",
    "openingId": "string",
    "createdAt": "string"
  },
  "action": "added"
}
200 OK - Removed from Favorites
{
  "action": "removed"
}
200 OK - Already in Favorites
{
  "message": "Already in favorites"
}
400 Bad Request - Validation Error
{
  "error": "Missing openingId or action"
}
GET
/api/user/favorites

Retrieves a paginated list of the authenticated user's favorite openings.

Query Parameters

page
number (optional, default: 1)
limit
number (optional, default: 20)

Example Request

// Fetch first page with custom limit
const response = await fetch('/api/user/favorites?page=1&limit=10');
const data = await response.json();

console.log(data.favorites);    // Array of opening objects
console.log(data.total);        // Total number of favorites
console.log(data.page);         // Current page number
console.log(data.totalPages);   // Total number of pages

Success Response

{
  "favorites": [
    {
      "id": "string",
      "name": "Ruy Lopez",
      "eco": "C60",
      "fen": "string",
      "pgn": "string",
      "totalFavorites": 15,
      "aliases": [
        {
          "id": "string",
          "name": "Spanish Opening",
          "openingId": "string"
        }
      ]
    }
  ],
  "total": 45,
  "page": 1,
  "totalPages": 3
}

Business Logic

  • Duplicate Prevention: API prevents duplicate favorites by checking existence before adding
  • Atomic Counters: The totalFavorites counter on openings is automatically incremented/decremented
  • Pagination: Results are paginated to optimize performance for large datasets
  • Data Integrity: All operations maintain referential integrity between users, favorites, and openings