You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.0 KiB

4 years ago
4 years ago
4 years ago
4 years ago
  1. package api
  2. import (
  3. "git.aiterp.net/lucifer/new-server/app/config"
  4. "git.aiterp.net/lucifer/new-server/models"
  5. "github.com/gin-gonic/gin"
  6. "log"
  7. )
  8. func Bridges(r gin.IRoutes) {
  9. r.GET("", handler(func(c *gin.Context) (interface{}, error) {
  10. return config.BridgeRepository().FetchAll(ctxOf(c))
  11. }))
  12. r.GET("/:id", handler(func(c *gin.Context) (interface{}, error) {
  13. return config.BridgeRepository().Find(ctxOf(c), intParam(c, "id"))
  14. }))
  15. r.POST("", handler(func(c *gin.Context) (interface{}, error) {
  16. var body struct {
  17. Driver models.DriverKind `json:"driver"`
  18. Address string `json:"address"`
  19. DryRun bool `json:"dryRun"`
  20. }
  21. err := parseBody(c, &body)
  22. if err != nil {
  23. return nil, err
  24. }
  25. driver, err := config.DriverProvider().Provide(body.Driver)
  26. if err != nil {
  27. return nil, err
  28. }
  29. bridges, err := driver.SearchBridge(ctxOf(c), body.Address, body.DryRun)
  30. if err != nil {
  31. return nil, err
  32. }
  33. if !body.DryRun {
  34. for _, bridge := range bridges {
  35. err := config.BridgeRepository().Save(ctxOf(c), &bridge)
  36. if err != nil {
  37. return nil, err
  38. }
  39. log.Printf("Saved new bridge: %s (%s)", bridge.Name, bridge.Address)
  40. }
  41. }
  42. return bridges, nil
  43. }))
  44. r.PUT("/:id", handler(func(c *gin.Context) (interface{}, error) {
  45. var body struct {
  46. Name *string `json:"name"`
  47. }
  48. err := parseBody(c, &body)
  49. if err != nil {
  50. return nil, err
  51. }
  52. bridge, err := config.BridgeRepository().Find(ctxOf(c), intParam(c, "id"))
  53. if err != nil {
  54. return nil, err
  55. }
  56. if body.Name != nil {
  57. bridge.Name = *body.Name
  58. }
  59. err = config.BridgeRepository().Save(ctxOf(c), &bridge)
  60. if err != nil {
  61. return nil, err
  62. }
  63. return bridge, nil
  64. }))
  65. r.DELETE("/:id", handler(func(c *gin.Context) (interface{}, error) {
  66. bridge, err := config.BridgeRepository().Find(ctxOf(c), intParam(c, "id"))
  67. if err != nil {
  68. return nil, err
  69. }
  70. err = config.BridgeRepository().Delete(ctxOf(c), &bridge)
  71. if err != nil {
  72. return nil, err
  73. }
  74. return bridge, nil
  75. }))
  76. }