create.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package cosy
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api/cosy/map2struct"
  4. "github.com/0xJacky/Nginx-UI/model"
  5. "github.com/gin-gonic/gin"
  6. "gorm.io/gorm/clause"
  7. "net/http"
  8. )
  9. func (c *Ctx[T]) Create() {
  10. errs := c.validate()
  11. if len(errs) > 0 {
  12. c.ctx.JSON(http.StatusNotAcceptable, gin.H{
  13. "message": "Requested with wrong parameters",
  14. "errors": errs,
  15. })
  16. return
  17. }
  18. db := model.UseDB()
  19. c.beforeDecodeHook()
  20. if c.abort {
  21. return
  22. }
  23. err := map2struct.WeakDecode(c.Payload, &c.Model)
  24. if err != nil {
  25. errHandler(c.ctx, err)
  26. return
  27. }
  28. c.beforeExecuteHook()
  29. if c.abort {
  30. return
  31. }
  32. // skip all associations
  33. err = db.Omit(clause.Associations).Create(&c.Model).Error
  34. if err != nil {
  35. errHandler(c.ctx, err)
  36. return
  37. }
  38. tx := db.Preload(clause.Associations)
  39. for _, v := range c.preloads {
  40. tx = tx.Preload(v)
  41. }
  42. tx.First(&c.Model)
  43. if len(c.executedHookFunc) > 0 {
  44. for _, v := range c.executedHookFunc {
  45. v(c)
  46. if c.abort {
  47. return
  48. }
  49. }
  50. }
  51. if c.nextHandler != nil {
  52. (*c.nextHandler)(c.ctx)
  53. } else {
  54. c.ctx.JSON(http.StatusOK, c.Model)
  55. }
  56. }