package api import ( "git.aiterp.net/lucifer/new-server/app/config" "git.aiterp.net/lucifer/new-server/models" "github.com/gin-gonic/gin" "log" ) func Bridges(r gin.IRoutes) { r.GET("", handler(func(c *gin.Context) (interface{}, error) { return config.BridgeRepository().FetchAll(ctxOf(c)) })) r.POST("", handler(func(c *gin.Context) (interface{}, error) { var body struct { Driver models.DriverKind `json:"driver"` Address string `json:"address"` DryRun bool `json:"dryRun"` } err := parseBody(c, &body) if err != nil { return nil, err } driver, err := config.DriverProvider().Provide(body.Driver) if err != nil { return nil, err } bridges, err := driver.SearchBridge(ctxOf(c), body.Address, body.DryRun) if err != nil { return nil, err } if !body.DryRun { for _, bridge := range bridges { err := config.BridgeRepository().Save(ctxOf(c), &bridge) if err != nil { return nil, err } log.Printf("Saved new bridge: %s (%s)", bridge.Name, bridge.Address) } } return bridges, nil })) r.PUT("/:id", handler(func(c *gin.Context) (interface{}, error) { var body struct { Name *string `json:"name"` } err := parseBody(c, &body) if err != nil { return nil, err } bridge, err := config.BridgeRepository().Find(ctxOf(c), intParam(c, "id")) if err != nil { return nil, err } if body.Name != nil { bridge.Name = *body.Name } err = config.BridgeRepository().Save(ctxOf(c), &bridge) if err != nil { return nil, err } return bridge, nil })) r.DELETE("/:id", handler(func(c *gin.Context) (interface{}, error) { bridge, err := config.BridgeRepository().Find(ctxOf(c), intParam(c, "id")) if err != nil { return nil, err } err = config.BridgeRepository().Delete(ctxOf(c), &bridge) if err != nil { return nil, err } return bridge, nil })) }