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.

89 lines
1.9 KiB

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.POST("", handler(func(c *gin.Context) (interface{}, error) {
  13. var body struct {
  14. Driver models.DriverKind `json:"driver"`
  15. Address string `json:"address"`
  16. DryRun bool `json:"dryRun"`
  17. }
  18. err := parseBody(c, &body)
  19. if err != nil {
  20. return nil, err
  21. }
  22. driver, err := config.DriverProvider().Provide(body.Driver)
  23. if err != nil {
  24. return nil, err
  25. }
  26. bridges, err := driver.SearchBridge(ctxOf(c), body.Address, body.DryRun)
  27. if err != nil {
  28. return nil, err
  29. }
  30. if !body.DryRun {
  31. for _, bridge := range bridges {
  32. err := config.BridgeRepository().Save(ctxOf(c), &bridge)
  33. if err != nil {
  34. return nil, err
  35. }
  36. log.Printf("Saved new bridge: %s (%s)", bridge.Name, bridge.Address)
  37. }
  38. }
  39. return bridges, nil
  40. }))
  41. r.PUT("/:id", handler(func(c *gin.Context) (interface{}, error) {
  42. var body struct {
  43. Name *string `json:"name"`
  44. }
  45. err := parseBody(c, &body)
  46. if err != nil {
  47. return nil, err
  48. }
  49. bridge, err := config.BridgeRepository().Find(ctxOf(c), intParam(c, "id"))
  50. if err != nil {
  51. return nil, err
  52. }
  53. if body.Name != nil {
  54. bridge.Name = *body.Name
  55. }
  56. err = config.BridgeRepository().Save(ctxOf(c), &bridge)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return bridge, nil
  61. }))
  62. r.DELETE("/:id", handler(func(c *gin.Context) (interface{}, error) {
  63. bridge, err := config.BridgeRepository().Find(ctxOf(c), intParam(c, "id"))
  64. if err != nil {
  65. return nil, err
  66. }
  67. err = config.BridgeRepository().Delete(ctxOf(c), &bridge)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return bridge, nil
  72. }))
  73. }