backend: add car
This commit is contained in:
69
go-backend/internal/repositories/car_repository.go
Normal file
69
go-backend/internal/repositories/car_repository.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"GoMembership/internal/database"
|
||||
"GoMembership/internal/models"
|
||||
"GoMembership/pkg/errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CarRepository interface defines the CRUD operations
|
||||
type CarRepositoryInterface interface {
|
||||
Create(car *models.Car) (*models.Car, error)
|
||||
GetByID(id uint) (*models.Car, error)
|
||||
GetAll() ([]models.Car, error)
|
||||
Update(car *models.Car) (*models.Car, error)
|
||||
Delete(id uint) error
|
||||
}
|
||||
|
||||
type CarRepository struct{}
|
||||
|
||||
// Create a new car
|
||||
func (r *CarRepository) Create(car *models.Car) (*models.Car, error) {
|
||||
if err := database.DB.Create(car).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return car, nil
|
||||
}
|
||||
|
||||
// GetByID fetches a car by its ID
|
||||
func (r *CarRepository) GetByID(id uint) (*models.Car, error) {
|
||||
var car models.Car
|
||||
if err := database.DB.Where("id = ?", id).First(&car).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &car, nil
|
||||
}
|
||||
|
||||
// GetAll retrieves all cars
|
||||
func (r *CarRepository) GetAll() ([]models.Car, error) {
|
||||
var cars []models.Car
|
||||
if err := database.DB.Find(&cars).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cars, nil
|
||||
}
|
||||
|
||||
// Update an existing car
|
||||
func (r *CarRepository) Update(car *models.Car) (*models.Car, error) {
|
||||
if err := database.DB.Save(car).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return car, nil
|
||||
}
|
||||
|
||||
// Delete a car (soft delete)
|
||||
func (r *CarRepository) Delete(id uint) error {
|
||||
result := database.DB.Delete(&models.Car{}, id)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return errors.ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user