create.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package cosy
  2. import (
  3. "github.com/0xJacky/Nginx-UI/internal/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. if c.skipAssociationsOnCreate {
  33. err = db.Omit(clause.Associations).Create(&c.Model).Error
  34. } else {
  35. err = db.Create(&c.Model).Error
  36. }
  37. if err != nil {
  38. errHandler(c.ctx, err)
  39. return
  40. }
  41. if len(c.executedHookFunc) > 0 {
  42. for _, v := range c.executedHookFunc {
  43. v(c)
  44. if c.abort {
  45. return
  46. }
  47. }
  48. }
  49. tx := db.Preload(clause.Associations)
  50. for _, v := range c.preloads {
  51. tx = tx.Preload(v)
  52. }
  53. tx.Table(c.table, c.tableArgs...).First(&c.Model)
  54. if c.nextHandler != nil {
  55. (*c.nextHandler)(c.ctx)
  56. } else {
  57. c.ctx.JSON(http.StatusOK, c.Model)
  58. }
  59. }
  60. func (c *Ctx[T]) WithAssociations() *Ctx[T] {
  61. c.skipAssociationsOnCreate = false
  62. return c
  63. }