environment.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package cluster
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/0xJacky/Nginx-UI/internal/analytic"
  6. "github.com/0xJacky/Nginx-UI/internal/cluster"
  7. "github.com/0xJacky/Nginx-UI/model"
  8. "github.com/0xJacky/Nginx-UI/query"
  9. "github.com/0xJacky/Nginx-UI/settings"
  10. "github.com/gin-gonic/gin"
  11. "github.com/spf13/cast"
  12. "github.com/uozi-tech/cosy"
  13. "gorm.io/gorm"
  14. )
  15. func GetEnvironment(c *gin.Context) {
  16. id := cast.ToUint64(c.Param("id"))
  17. envQuery := query.Environment
  18. env, err := envQuery.FirstByID(id)
  19. if err != nil {
  20. cosy.ErrHandler(c, err)
  21. return
  22. }
  23. c.JSON(http.StatusOK, analytic.GetNode(env))
  24. }
  25. func GetEnvironmentList(c *gin.Context) {
  26. core := cosy.Core[model.Environment](c).
  27. SetFussy("name")
  28. // fix for sqlite
  29. if c.Query("enabled") != "" {
  30. core.GormScope(func(tx *gorm.DB) *gorm.DB {
  31. return tx.Where("enabled = ?", cast.ToInt(cast.ToBool(c.Query("enabled"))))
  32. })
  33. }
  34. core.SetTransformer(func(m *model.Environment) any {
  35. return analytic.GetNode(m)
  36. })
  37. data, ok := core.ListAllData()
  38. if !ok {
  39. return
  40. }
  41. c.JSON(http.StatusOK, model.DataList{
  42. Data: data,
  43. })
  44. }
  45. func AddEnvironment(c *gin.Context) {
  46. cosy.Core[model.Environment](c).SetValidRules(gin.H{
  47. "name": "required",
  48. "url": "required,url",
  49. "token": "required",
  50. "enabled": "omitempty,boolean",
  51. }).ExecutedHook(func(c *cosy.Ctx[model.Environment]) {
  52. go analytic.RestartRetrieveNodesStatus()
  53. }).Create()
  54. }
  55. func EditEnvironment(c *gin.Context) {
  56. cosy.Core[model.Environment](c).SetValidRules(gin.H{
  57. "name": "required",
  58. "url": "required,url",
  59. "token": "required",
  60. "enabled": "omitempty,boolean",
  61. }).ExecutedHook(func(c *cosy.Ctx[model.Environment]) {
  62. go analytic.RestartRetrieveNodesStatus()
  63. }).Modify()
  64. }
  65. func DeleteEnvironment(c *gin.Context) {
  66. cosy.Core[model.Environment](c).
  67. ExecutedHook(func(c *cosy.Ctx[model.Environment]) {
  68. go analytic.RestartRetrieveNodesStatus()
  69. }).Destroy()
  70. }
  71. func LoadEnvironmentFromSettings(c *gin.Context) {
  72. err := settings.ReloadCluster()
  73. if err != nil {
  74. cosy.ErrHandler(c, err)
  75. return
  76. }
  77. ctx := context.Background()
  78. cluster.RegisterPredefinedNodes(ctx)
  79. go analytic.RestartRetrieveNodesStatus()
  80. c.JSON(http.StatusOK, gin.H{
  81. "message": "ok",
  82. })
  83. }