feat: Add API endpoint to create storage spaces

This commit is contained in:
garionion (aider) 2025-02-28 21:46:13 +01:00
parent 081020b809
commit 699dca3328
2 changed files with 71 additions and 0 deletions

View file

@ -185,9 +185,77 @@ func (h *StorageHandler) getChildStorageIDs(spaces []db.Storagespace, parentID i
return childIDs
}
// CreateStorageSpace creates a new storage space
func (h *StorageHandler) CreateStorageSpace(c echo.Context) error {
ctx := context.Background()
// Parse request body
type StorageSpaceRequest struct {
Location string `json:"location"`
Parent *struct {
Valid bool `json:"valid"`
Int64 int64 `json:"int64"`
} `json:"parent"`
}
var req StorageSpaceRequest
if err := c.Bind(&req); err != nil {
h.logger.Warn("Invalid request body", zap.Error(err))
return c.JSON(http.StatusBadRequest, map[string]string{
"error": "Invalid request body",
})
}
// Convert parent to sql.NullInt64
var parent sql.NullInt64
if req.Parent != nil && req.Parent.Valid {
parent.Valid = true
parent.Int64 = req.Parent.Int64
// Verify parent exists
_, err := h.db.GetStorageSpaceByID(ctx, parent.Int64)
if err != nil {
if err == sql.ErrNoRows {
return c.JSON(http.StatusBadRequest, map[string]string{
"error": "Parent storage space not found",
})
}
h.logger.Error("Failed to fetch parent storage space", zap.Error(err))
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": "Failed to verify parent storage space",
})
}
}
// Convert location to sql.NullString
var location sql.NullString
if req.Location != "" {
location.Valid = true
location.String = req.Location
}
// Create storage space
err := h.db.CreateStorageSpace(ctx, db.CreateStorageSpaceParams{
Parent: parent,
Location: location,
})
if err != nil {
h.logger.Error("Failed to create storage space", zap.Error(err))
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": "Failed to create storage space",
})
}
return c.JSON(http.StatusCreated, map[string]string{
"message": "Storage space created successfully",
})
}
// RegisterRoutes registers all storage-related routes
func (h *StorageHandler) RegisterRoutes(g *echo.Group) {
g.GET("/storageSpaces", h.GetStorageSpaces)
g.POST("/storageSpaces", h.CreateStorageSpace)
g.GET("/storageSpaces/:id/objects", h.GetObjectsInStorage)
g.GET("/storageSpaces/:id/hierarchy/objects", h.GetStorageHierarchyObjects)
}

View file

@ -67,3 +67,6 @@ SELECT id, parent, location FROM storagespace WHERE parent = ?;
-- name: GetObjectsByStorageID :many
SELECT id, storagespace_id, name, description, serialnumber, created
FROM objects WHERE storagespace_id = ?;
-- name: CreateStorageSpace :exec
INSERT INTO storagespace (parent, location) VALUES (?, ?);