feat: better API returns, asset update

This commit is contained in:
2024-01-21 01:02:40 -06:00
parent a8ee837dee
commit b2c8c2915f
7 changed files with 93 additions and 10 deletions

View File

@@ -7,6 +7,7 @@ import (
"git.brettb.xyz/goinv/server/internal/types"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
)
@@ -47,6 +48,11 @@ func (s *DataStore) CreateAsset(asset *types.Asset) error {
return result.Error
}
func (s *DataStore) UpdateAsset(id uint64, update *types.Asset) error {
result := s.db.Model(&types.Asset{}).Where("id = ?", id).Select("*").Updates(update)
return result.Error
}
func (s *DataStore) CreateBuilding(building *types.Building) error {
result := s.db.Create(building)
return result.Error
@@ -64,7 +70,7 @@ func (s *DataStore) CreateShelfLocation(shelf *types.ShelfLocation) error {
func (s *DataStore) GetAssetByID(id uint64) (*types.Asset, error) {
var result types.Asset
tx := s.db.Model(&types.Asset{}).Where("id = ?", id).First(&result)
tx := s.db.Model(&types.Asset{}).Where("id = ?", id).Preload(clause.Associations).First(&result)
if tx.Error != nil {
return nil, fmt.Errorf("asset %d not found", id)
}
@@ -88,6 +94,14 @@ func (s *DataStore) TotalAssets() (int64, error) {
return count, nil
}
func (s *DataStore) AssetCountInLocation(shelfId uint64) (int64, error) {
var count int64
if tx := s.db.Model(&types.Asset{}).Where("shelf_location_id = ?", shelfId).Find(&types.Asset{}).Count(&count); tx.Error != nil {
return 0, tx.Error
}
return count, nil
}
func (s *DataStore) DeleteAssetByID(id uint64) (bool, error) {
tx := s.db.Delete(&types.Asset{}, id)
if tx.Error != nil {
@@ -98,16 +112,16 @@ func (s *DataStore) DeleteAssetByID(id uint64) (bool, error) {
func (s *DataStore) GetShelfByID(id uint64) (*types.ShelfLocation, error) {
var result types.ShelfLocation
tx := s.db.Model(&types.ShelfLocation{}).Where("id = ?", id).First(&result)
tx := s.db.Joins("Building").Where(&types.ShelfLocation{ID: id}).First(&result)
if tx.Error != nil {
return nil, fmt.Errorf("shelf %d not found", id)
return nil, fmt.Errorf("shelf %d not found: %v", id, tx.Error)
}
return &result, nil
}
func (s *DataStore) GetShelves(offset, limit int) ([]*types.ShelfLocation, error) {
func (s *DataStore) GetShelves(offset, limit uint64) ([]*types.ShelfLocation, error) {
var shelves []*types.ShelfLocation
s.db.Offset(offset).Limit(limit).Find(&shelves)
s.db.Joins("Building").Order("id asc").Offset(int(offset)).Limit(int(limit)).Find(&shelves)
if len(shelves) == 0 {
return nil, fmt.Errorf("no shelves found")
}