feat: add hosts management

This commit is contained in:
2024-11-09 10:33:07 +00:00
parent 31c43836f4
commit d931235fb3
27 changed files with 742 additions and 94 deletions
+15 -1
View File
@@ -14,7 +14,7 @@ func NewHostsRepository() *Hosts {
func (r *Hosts) GetAll() ([]*models.Host, error) {
var rows []*models.Host
ret := r.db.Order("created_at DESC").Find(&rows)
ret := r.db.Order("id DESC").Find(&rows)
return rows, ret.Error
}
@@ -49,6 +49,20 @@ func (r *Hosts) Get(id string) (*GetHostResult, error) {
return res, ret.Error
}
func (r *Hosts) Exists(id string) (bool, error) {
var count int64
ret := r.db.Model(&models.Host{}).Where("id = ?", id).Count(&count)
return count > 0, ret.Error
}
func (r *Hosts) Delete(id string) error {
return r.db.Delete(&models.Host{Model: models.Model{ID: id}}).Error
}
func (r *Hosts) Create(item *models.Host) error {
return r.db.Create(item).Error
}
func (r *Hosts) Update(item *models.Host) error {
return r.db.Save(item).Error
}
+54 -1
View File
@@ -1,6 +1,7 @@
package hosts
import (
"fmt"
"net/http"
"github.com/gofiber/fiber/v2"
@@ -13,6 +14,8 @@ func Router(app *fiber.App) {
router.Get("/", getAll)
router.Post("/", create)
router.Put("/:id", update)
router.Delete("/:id", delete)
}
func getAll(c *fiber.Ctx) error {
@@ -34,7 +37,6 @@ func create(c *fiber.Ctx) error {
}
repo := NewHostsRepository()
item := &models.Host{
Type: body.Type,
Label: body.Label,
@@ -51,3 +53,54 @@ func create(c *fiber.Ctx) error {
return c.Status(http.StatusCreated).JSON(item)
}
func update(c *fiber.Ctx) error {
var body CreateHostSchema
if err := c.BodyParser(&body); err != nil {
return utils.ResponseError(c, err, 500)
}
repo := NewHostsRepository()
id := c.Params("id")
exist, _ := repo.Exists(id)
if !exist {
return utils.ResponseError(c, fmt.Errorf("host %s not found", id), 404)
}
item := &models.Host{
Model: models.Model{ID: id},
Type: body.Type,
Label: body.Label,
Host: body.Host,
Port: body.Port,
Metadata: body.Metadata,
ParentID: body.ParentID,
KeyID: body.KeyID,
AltKeyID: body.AltKeyID,
}
if err := repo.Update(item); err != nil {
return utils.ResponseError(c, err, 500)
}
return c.JSON(item)
}
func delete(c *fiber.Ctx) error {
repo := NewHostsRepository()
id := c.Params("id")
exist, _ := repo.Exists(id)
if !exist {
return utils.ResponseError(c, fmt.Errorf("host %s not found", id), 404)
}
if err := repo.Delete(id); err != nil {
return utils.ResponseError(c, err, 500)
}
return c.JSON(fiber.Map{
"status": "ok",
"message": "Successfully deleted",
})
}
+1
View File
@@ -13,6 +13,7 @@ import (
)
type IncusWebsocketSession struct {
Type string `json:"type"` // "qemu" | "lxc"
Instance string `json:"instance"`
Shell string `json:"shell"`
}