github.com/iron-io/functions@v0.0.0-20180820112432-d59d7d1c40b2/api/server/routes_create.go (about) 1 package server 2 3 import ( 4 "context" 5 "net/http" 6 7 "github.com/gin-gonic/gin" 8 "github.com/iron-io/functions/api" 9 "github.com/iron-io/functions/api/models" 10 "github.com/iron-io/runner/common" 11 ) 12 13 func (s *Server) handleRouteCreate(c *gin.Context) { 14 ctx := c.MustGet("ctx").(context.Context) 15 log := common.Logger(ctx) 16 17 var wroute models.RouteWrapper 18 19 err := c.BindJSON(&wroute) 20 if err != nil { 21 log.WithError(err).Debug(models.ErrInvalidJSON) 22 c.JSON(http.StatusBadRequest, simpleError(models.ErrInvalidJSON)) 23 return 24 } 25 26 if wroute.Route == nil { 27 log.WithError(err).Debug(models.ErrInvalidJSON) 28 c.JSON(http.StatusBadRequest, simpleError(models.ErrRoutesMissingNew)) 29 return 30 } 31 32 wroute.Route.AppName = c.MustGet(api.AppName).(string) 33 34 wroute.Route.SetDefaults() 35 36 if err := wroute.Validate(false); err != nil { 37 log.WithError(err).Debug(models.ErrRoutesCreate) 38 c.JSON(http.StatusBadRequest, simpleError(err)) 39 return 40 } 41 42 // err = s.Runner.EnsureImageExists(ctx, &task.Config{ 43 // Image: wroute.Route.Image, 44 // }) 45 // if err != nil { 46 // c.JSON(http.StatusBadRequest, simpleError(models.ErrUsableImage)) 47 // return 48 // } 49 50 app, err := s.Datastore.GetApp(ctx, wroute.Route.AppName) 51 if err != nil && err != models.ErrAppsNotFound { 52 log.WithError(err).Error(models.ErrAppsGet) 53 c.JSON(http.StatusInternalServerError, simpleError(models.ErrAppsGet)) 54 return 55 } else if app == nil { 56 // Create a new application and add the route to that new application 57 newapp := &models.App{Name: wroute.Route.AppName} 58 if err := newapp.Validate(); err != nil { 59 log.Error(err) 60 c.JSON(http.StatusInternalServerError, simpleError(err)) 61 return 62 } 63 64 err = s.FireBeforeAppCreate(ctx, newapp) 65 if err != nil { 66 log.WithError(err).Error(models.ErrAppsCreate) 67 c.JSON(http.StatusInternalServerError, simpleError(ErrInternalServerError)) 68 return 69 } 70 71 _, err = s.Datastore.InsertApp(ctx, newapp) 72 if err != nil { 73 log.WithError(err).Error(models.ErrRoutesCreate) 74 c.JSON(http.StatusInternalServerError, simpleError(ErrInternalServerError)) 75 return 76 } 77 78 err = s.FireAfterAppCreate(ctx, newapp) 79 if err != nil { 80 log.WithError(err).Error(models.ErrRoutesCreate) 81 c.JSON(http.StatusInternalServerError, simpleError(ErrInternalServerError)) 82 return 83 } 84 85 } 86 87 route, err := s.Datastore.InsertRoute(ctx, wroute.Route) 88 if err != nil { 89 handleErrorResponse(c, err) 90 return 91 } 92 93 s.cacherefresh(route) 94 95 c.JSON(http.StatusOK, routeResponse{"Route successfully created", route}) 96 }