ApiController.java

  1. package edu.ucsb.cs156.example.controllers;

  2. import edu.ucsb.cs156.example.errors.EntityNotFoundException;
  3. import org.springframework.beans.factory.annotation.Autowired;

  4. import edu.ucsb.cs156.example.models.CurrentUser;
  5. import edu.ucsb.cs156.example.services.CurrentUserService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.http.HttpStatus;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.ResponseStatus;

  10. import java.util.Map;

  11. /**
  12.  * This is an abstract class that provides common functionality for all API controllers.
  13.  */

  14. @Slf4j
  15. public abstract class ApiController {
  16.   @Autowired
  17.   private CurrentUserService currentUserService;

  18.   /**
  19.    * This method returns the current user.
  20.    * @return the current user
  21.    */
  22.   protected CurrentUser getCurrentUser() {
  23.     return currentUserService.getCurrentUser();
  24.   }

  25.   /**
  26.    * This method returns a generic message.
  27.    * @param message the message
  28.    * @return a map with the message
  29.    */
  30.   protected Object genericMessage(String message) {
  31.     return Map.of("message", message);
  32.   }

  33.   /**
  34.    * This method handles the EntityNotFoundException.
  35.    * @param e the exception
  36.    * @return a map with the type and message of the exception
  37.    */
  38.   @ExceptionHandler({ EntityNotFoundException.class })
  39.   @ResponseStatus(HttpStatus.NOT_FOUND)
  40.   public Object handleGenericException(Throwable e) {
  41.     return Map.of(
  42.       "type", e.getClass().getSimpleName(),
  43.       "message", e.getMessage()
  44.     );
  45.   }
  46. }