dimanche 27 août 2023

What should the service layer return to the controller when validating data in service layer?

I have a small car API that is made up of a controller, service and repository I want to validate the data from within the service layer and return the 200, 404 or 400 with a little message saying what the problem is from the service. In other words, I want to move all the logic from the controller to the service layer.

How can I return a status code and if it's an error what caused the error, from the service layer to the controller?

API Controller method:

        [HttpGet("GetById/{Id:int}", Name = "GetCar")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]

        public IActionResult GetById(int Id)
        {
            if (Id < 1)
            {
                ModelState.AddModelError("CarIdIsZero", "Car Id Must Not Be Less Than One !");
                return BadRequest(ModelState);
            }

            var car = _db.Car.FirstOrDefault(u => u.Id == Id);

            if (car == null)
            {
                ModelState.AddModelError("CarNotFound", "Car was not found !");
                return NotFound(ModelState);
            }

            return Ok(car);

        }

Service Layer Method:

public IActionResult GetById(int carId)
        {
            return;
        }

Repository Layer Method:

    public IEnumerable<Car> Get()
        {
            return _db.Car;
        }
       

Aucun commentaire:

Enregistrer un commentaire