From 5dcdcd21db3a52332345ecd1313df5cc69284deb Mon Sep 17 00:00:00 2001 From: Olin Date: Sun, 27 Feb 2022 12:10:46 -0700 Subject: [PATCH 01/22] add empty routes and controllers files --- src/rest/controllers/device.go | 1 + src/rest/routes/device.go | 1 + 2 files changed, 2 insertions(+) create mode 100644 src/rest/controllers/device.go create mode 100644 src/rest/routes/device.go diff --git a/src/rest/controllers/device.go b/src/rest/controllers/device.go new file mode 100644 index 00000000..2d329367 --- /dev/null +++ b/src/rest/controllers/device.go @@ -0,0 +1 @@ +package controllers diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go new file mode 100644 index 00000000..0db51ae5 --- /dev/null +++ b/src/rest/routes/device.go @@ -0,0 +1 @@ +package routes From 2e5a4875d9d6d14f70434ea42a39cb30eb73ed6d Mon Sep 17 00:00:00 2001 From: Olin Date: Sun, 27 Feb 2022 16:50:38 -0700 Subject: [PATCH 02/22] move all existing rest endpoints into new route controller pattern --- src/app/app.go | 23 ++++++++++-- src/rest/controllers/device.go | 67 ++++++++++++++++++++++++++++++++++ src/rest/routes/device.go | 16 ++++++++ src/rest/routes/routes.go | 41 +++++++++++++++++++++ src/routes/cluster_info.go | 54 --------------------------- src/routes/registration.go | 33 ----------------- src/routes/routes.go | 10 ----- 7 files changed, 143 insertions(+), 101 deletions(-) create mode 100644 src/rest/routes/routes.go delete mode 100644 src/routes/cluster_info.go delete mode 100644 src/routes/registration.go diff --git a/src/app/app.go b/src/app/app.go index 20bdf4b7..eb1b2f71 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -6,7 +6,9 @@ import ( "github.com/rna-vt/devicecommander/src/cluster" "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/endpoint" - "github.com/rna-vt/devicecommander/src/routes" + + "github.com/rna-vt/devicecommander/src/rest/routes" + log "github.com/sirupsen/logrus" ) // The Application encapsulates the required state for the running software. @@ -24,9 +26,22 @@ func (a *Application) SystemInfo() string { } func (a *Application) Start() { - api := routes.NewAPIService(&a.Cluster, a.DeviceRepository, a.EndpointRepository) + a.startListening() + a.startMaintainingCluster() +} - a.Cluster.Start() +func (a *Application) startListening() { + routes.BaseRouter{}.RegisterRoutes(a.Echo) + log.Info("Configured routes listening on " + a.Hostname) + + log.Println("*****************************************************") + log.Println("~Rejoice~ The Device Commander Lives Again! ~Rejoice~") + log.Println("*****************************************************") - api.ConfigureRoutes(a.Hostname, a.Echo) + // Start server + a.Echo.Logger.Fatal(a.Echo.Start(a.Hostname)) +} + +func (a *Application) startMaintainingCluster() { + a.Cluster.Start() } diff --git a/src/rest/controllers/device.go b/src/rest/controllers/device.go index 2d329367..e93b5fd9 100644 --- a/src/rest/controllers/device.go +++ b/src/rest/controllers/device.go @@ -1 +1,68 @@ package controllers + +import ( + "net/http" + + "github.com/google/uuid" + "github.com/labstack/echo" + "github.com/labstack/gommon/log" + "github.com/rna-vt/devicecommander/graph/model" + "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/postgres" + postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" +) + +type DeviceController struct { + Repository device.Repository +} + +func NewDeviceController() (DeviceController, error) { + dbConfig := postgres.GetDBConfigFromEnv() + deviceRepository, err := postgresDevice.NewRepository(dbConfig) + if err != nil { + log.Error(err) + return DeviceController{}, err + } + + return DeviceController{ + Repository: deviceRepository, + }, nil +} + +func (controller DeviceController) Create(c echo.Context) error { + dev, err := device.BasicDevice{}.NewDeviceFromRequestBody(c.Request().Body) + if err != nil { + return err + } + + newDevice, err := controller.Repository.Create(dev) + if err != nil { + return err + } + + return c.JSON(http.StatusOK, newDevice) +} + +func (controller DeviceController) GetAll(c echo.Context) error { + devices, err := controller.Repository.GetAll() + if err != nil { + return err + } + + return c.JSON(http.StatusOK, devices) +} + +func (controller DeviceController) GetDevice(c echo.Context) error { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + return err + } + + tmpDev := model.Device{ID: id} + device, err := controller.Repository.Get(tmpDev) + if err != nil { + return err + } + + return c.JSON(http.StatusOK, &device) +} diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index 0db51ae5..381a3cf6 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -1 +1,17 @@ package routes + +import ( + "github.com/labstack/echo" + "github.com/rna-vt/devicecommander/src/rest/controllers" +) + +type DeviceRouter struct { + DeviceController controllers.DeviceController +} + +func (r DeviceRouter) RegisterRoutes(e *echo.Echo) { + api := e.Group("/v1/device") + api.POST("/", r.DeviceController.Create) + api.GET("/", r.DeviceController.GetAll) + api.GET("/device/:id", r.DeviceController.GetDevice) +} diff --git a/src/rest/routes/routes.go b/src/rest/routes/routes.go new file mode 100644 index 00000000..456ae285 --- /dev/null +++ b/src/rest/routes/routes.go @@ -0,0 +1,41 @@ +package routes + +import ( + "github.com/labstack/echo" + "github.com/labstack/echo/middleware" + "github.com/spf13/viper" +) + +type Router interface{} + +type BaseRouter struct{} + +func (r BaseRouter) RegisterRoutes(e *echo.Echo) { + // Middleware + e.Use(middleware.Logger()) + e.Use(middleware.Recover()) + + // CORS restricted + // wth GET, PUT, POST or DELETE method. + e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ + AllowOrigins: []string{"*"}, + })) + + r.registerFrontendRoutes(e) + r.registerBackendRoutes(e) +} + +func (r BaseRouter) registerFrontendRoutes(e *echo.Echo) { + frontendRoot := "../frontend/build/" + if viper.GetString("ENV") == "production" { + frontendRoot = "/src/build/" + } + + // Routes + e.Static("/static", frontendRoot+"static") + e.File("/*", frontendRoot+"index.html") +} + +func (r BaseRouter) registerBackendRoutes(e *echo.Echo) { + DeviceRouter{}.RegisterRoutes(e) +} diff --git a/src/routes/cluster_info.go b/src/routes/cluster_info.go deleted file mode 100644 index b3b7065c..00000000 --- a/src/routes/cluster_info.go +++ /dev/null @@ -1,54 +0,0 @@ -package routes - -import ( - "net/http" - - "github.com/google/uuid" - "github.com/labstack/echo" - - "github.com/rna-vt/devicecommander/graph/model" -) - -func (a *APIService) addInfoRoutes(e *echo.Echo) { - api := e.Group("/v1") - api.GET("/cluster_info", a.getClusterInfo) - api.GET("/device", a.getDevices) - api.GET("/device/:id", a.getDevice) - api.GET("/health", a.health) -} - -func (a APIService) health(c echo.Context) error { - return c.JSON(http.StatusOK, "I'm Alive") -} - -func (a APIService) getClusterInfo(c echo.Context) error { - devices, err := a.DeviceRepository.GetAll() - if err != nil { - return err - } - - return c.JSON(http.StatusOK, devices) -} - -func (a APIService) getDevices(c echo.Context) error { - devices, err := a.DeviceRepository.GetAll() - if err != nil { - return err - } - return c.JSON(http.StatusOK, devices) -} - -func (a *APIService) getDevice(c echo.Context) error { - id, err := uuid.Parse(c.Param("id")) - if err != nil { - return err - } - - tmpDev := model.Device{ID: id} - device, err := a.DeviceRepository.Get(tmpDev) - if err != nil { - return err - } - - return c.JSON(http.StatusOK, &device) -} diff --git a/src/routes/registration.go b/src/routes/registration.go deleted file mode 100644 index 93021f84..00000000 --- a/src/routes/registration.go +++ /dev/null @@ -1,33 +0,0 @@ -package routes - -import ( - "log" - "net/http" - - "github.com/labstack/echo" - - "github.com/rna-vt/devicecommander/src/device" -) - -func (a *APIService) addRegistrationRoutes(e *echo.Echo) { - api := e.Group("/v1") - api.POST("/join_network", a.joinNetwork) -} - -// joinNetwork enables self sign-up for devices that have previously connected -// and devices that need to be manually added. -func (a *APIService) joinNetwork(c echo.Context) error { - log.Println("Device asked to join cluster") - - dev, err := device.BasicDevice{}.NewDeviceFromRequestBody(c.Request().Body) - if err != nil { - return err - } - - newDevice, err := a.DeviceRepository.Create(dev) - if err != nil { - return err - } - - return c.JSON(http.StatusOK, newDevice) -} diff --git a/src/routes/routes.go b/src/routes/routes.go index 4d12222b..9b68b3fb 100644 --- a/src/routes/routes.go +++ b/src/routes/routes.go @@ -1,8 +1,6 @@ package routes import ( - "net/http" - "github.com/labstack/echo" "github.com/labstack/echo/middleware" log "github.com/sirupsen/logrus" @@ -52,10 +50,7 @@ func (api APIService) ConfigureRoutes(listenURL string, e *echo.Echo) { // Routes e.Static("/static", frontendRoot+"static") e.File("/*", frontendRoot+"index.html") - e.GET("/v1", api.defaultGet) - api.addRegistrationRoutes(e) - api.addInfoRoutes(e) api.addGraphQLRoutes(e, api.DeviceRepository, api.EndpointRepository) api.logger.Info("Configured routes listening on " + listenURL) @@ -67,8 +62,3 @@ func (api APIService) ConfigureRoutes(listenURL string, e *echo.Echo) { // Start server e.Logger.Fatal(e.Start(listenURL)) } - -func (api APIService) defaultGet(c echo.Context) error { - log.Println("Someone is touching me", api.Cluster) - return c.String(http.StatusOK, "Help Me! I'm trapped in the Server! You're the only one receiving this message.") -} From 31a52198dbf84879750a022387f862026e56d484 Mon Sep 17 00:00:00 2001 From: Olin Date: Sun, 27 Feb 2022 16:51:19 -0700 Subject: [PATCH 03/22] lint-fic --- src/app/app.go | 3 +-- src/rest/controllers/device.go | 1 + src/rest/routes/device.go | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/app/app.go b/src/app/app.go index eb1b2f71..eb527706 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -2,13 +2,12 @@ package app import ( "github.com/labstack/echo" + log "github.com/sirupsen/logrus" "github.com/rna-vt/devicecommander/src/cluster" "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/endpoint" - "github.com/rna-vt/devicecommander/src/rest/routes" - log "github.com/sirupsen/logrus" ) // The Application encapsulates the required state for the running software. diff --git a/src/rest/controllers/device.go b/src/rest/controllers/device.go index e93b5fd9..65a1f9e4 100644 --- a/src/rest/controllers/device.go +++ b/src/rest/controllers/device.go @@ -6,6 +6,7 @@ import ( "github.com/google/uuid" "github.com/labstack/echo" "github.com/labstack/gommon/log" + "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index 381a3cf6..673d8a7b 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -2,6 +2,7 @@ package routes import ( "github.com/labstack/echo" + "github.com/rna-vt/devicecommander/src/rest/controllers" ) From b9cb21b4956bcb7eee1d3c6afbd193b256b5b09b Mon Sep 17 00:00:00 2001 From: Olin Date: Tue, 26 Apr 2022 18:06:58 -0600 Subject: [PATCH 04/22] convert from graphQL to rest --- graph/device.resolvers.go | 64 - graph/device_test.go | 91 - graph/endpoint.resolvers.go | 46 - graph/generated/generated.go | 5278 ----------------- graph/model/device.go | 54 - graph/model/endpoint.go | 21 - graph/model/models.go | 53 - graph/resolver.go | 17 - graph/schemas/device.graphqls | 38 - graph/schemas/endpoint.graphqls | 50 - mocks/cluster/Cluster.go | 19 +- mocks/device/{Device.go => BasicDevice.go} | 58 +- mocks/device/Client.go | 18 +- .../Endpoint.go => device/DeviceEndpoint.go} | 6 +- mocks/device/EndpointRepository.go | 119 + mocks/device/ParameterRepository.go | 119 + mocks/device/Repository.go | 42 +- mocks/endpoint/Repository.go | 119 - mocks/parameter/Repository.go | 119 - mocks/rest/routes/Router.go | 10 + src/app/app.go | 3 +- src/cluster/cluster.go | 19 +- src/cluster/cluster_test.go | 16 +- src/cluster/registration.go | 25 +- src/cluster/registration_test.go | 14 +- src/device/client.go | 18 +- src/device/device.go | 120 +- src/device/device_test.go | 45 +- src/{endpoint => device}/endpoint.go | 32 +- src/device/endpoint_params.go | 16 + src/device/endpoint_repository.go | 11 + src/{endpoint => device}/endpoint_test.go | 20 +- src/device/health.go | 10 +- src/{parameter => device}/parameter.go | 16 +- src/device/parameter_params.go | 16 + src/device/parameter_repository.go | 11 + src/{parameter => device}/parameter_test.go | 30 +- src/device/params.go | 21 + src/device/repository.go | 12 +- src/{test => device}/utils.go | 36 +- src/docs/device_swagger.go | 4 +- src/endpoint/repository.go | 13 - src/parameter/repository.go | 13 - src/postgres/config.go | 5 +- src/postgres/device/device_repository.go | 27 +- src/postgres/device/device_repository_test.go | 30 +- src/postgres/endpoint/endpoint_repository.go | 27 +- .../endpoint/endpoint_repository_test.go | 34 +- .../parameter/parameter_repository.go | 25 +- .../parameter/parameter_repository_test.go | 30 +- src/rest/controllers/device.go | 30 +- src/rest/controllers/device_test.go | 108 + src/rest/routes/device.go | 3 +- src/routes/graphql.go | 37 - src/routes/routes.go | 64 - src/scanner/arp.go | 8 +- src/scanner/scanner.go | 17 +- src/test/utils_test.go | 70 - 58 files changed, 836 insertions(+), 6541 deletions(-) delete mode 100644 graph/device.resolvers.go delete mode 100644 graph/device_test.go delete mode 100644 graph/endpoint.resolvers.go delete mode 100644 graph/generated/generated.go delete mode 100644 graph/model/device.go delete mode 100644 graph/model/endpoint.go delete mode 100644 graph/model/models.go delete mode 100644 graph/resolver.go delete mode 100644 graph/schemas/device.graphqls delete mode 100644 graph/schemas/endpoint.graphqls rename mocks/device/{Device.go => BasicDevice.go} (51%) rename mocks/{endpoint/Endpoint.go => device/DeviceEndpoint.go} (66%) create mode 100644 mocks/device/EndpointRepository.go create mode 100644 mocks/device/ParameterRepository.go delete mode 100644 mocks/endpoint/Repository.go delete mode 100644 mocks/parameter/Repository.go create mode 100644 mocks/rest/routes/Router.go rename src/{endpoint => device}/endpoint.go (57%) create mode 100644 src/device/endpoint_params.go create mode 100644 src/device/endpoint_repository.go rename src/{endpoint => device}/endpoint_test.go (64%) rename src/{parameter => device}/parameter.go (55%) create mode 100644 src/device/parameter_params.go create mode 100644 src/device/parameter_repository.go rename src/{parameter => device}/parameter_test.go (54%) create mode 100644 src/device/params.go rename src/{test => device}/utils.go (55%) delete mode 100644 src/endpoint/repository.go delete mode 100644 src/parameter/repository.go create mode 100644 src/rest/controllers/device_test.go delete mode 100644 src/routes/graphql.go delete mode 100644 src/routes/routes.go delete mode 100644 src/test/utils_test.go diff --git a/graph/device.resolvers.go b/graph/device.resolvers.go deleted file mode 100644 index aed8d12a..00000000 --- a/graph/device.resolvers.go +++ /dev/null @@ -1,64 +0,0 @@ -package graph - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - - generated1 "github.com/rna-vt/devicecommander/graph/generated" - "github.com/rna-vt/devicecommander/graph/model" -) - -func (r *deviceResolver) ID(ctx context.Context, obj *model.Device) (string, error) { - return obj.ID.String(), nil -} - -func (r *mutationResolver) CreateDevice(ctx context.Context, input model.NewDevice) (*model.Device, error) { - newDevice, err := r.DeviceRepository.Create(input) - if err != nil { - return newDevice, err - } - - return newDevice, nil -} - -func (r *mutationResolver) UpdateDevice(ctx context.Context, input model.UpdateDevice) (string, error) { - err := r.DeviceRepository.Update(input) - if err != nil { - return "", err - } - return input.ID, nil -} - -func (r *mutationResolver) DeleteDevice(ctx context.Context, id string) (*model.Device, error) { - newDevice, err := r.DeviceRepository.Delete(id) - if err != nil { - return newDevice, err - } - - return newDevice, nil -} - -func (r *queryResolver) Devices(ctx context.Context) ([]*model.Device, error) { - devices, err := r.DeviceRepository.GetAll() - if err != nil { - return devices, err - } - return devices, nil -} - -// Device returns generated1.DeviceResolver implementation. -func (r *Resolver) Device() generated1.DeviceResolver { return &deviceResolver{r} } - -// Mutation returns generated1.MutationResolver implementation. -func (r *Resolver) Mutation() generated1.MutationResolver { return &mutationResolver{r} } - -// Query returns generated1.QueryResolver implementation. -func (r *Resolver) Query() generated1.QueryResolver { return &queryResolver{r} } - -type ( - deviceResolver struct{ *Resolver } - mutationResolver struct{ *Resolver } - queryResolver struct{ *Resolver } -) diff --git a/graph/device_test.go b/graph/device_test.go deleted file mode 100644 index 69bc01e4..00000000 --- a/graph/device_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package graph - -import ( - "context" - "testing" - - "github.com/google/uuid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - - "github.com/rna-vt/devicecommander/graph/model" - mocks "github.com/rna-vt/devicecommander/mocks/device" - "github.com/rna-vt/devicecommander/src/test" -) - -type DeviceGraphQLSuite struct { - suite.Suite - resolver Resolver - mockDeviceRepository mocks.Repository - ctx context.Context -} - -func (s *DeviceGraphQLSuite) SetupSuite() { - s.mockDeviceRepository = mocks.Repository{} - s.resolver = Resolver{ - DeviceRepository: &s.mockDeviceRepository, - } - s.ctx = context.Background() -} - -func (s *DeviceGraphQLSuite) TestCreateDevice() { - mutator := s.resolver.Mutation() - newDevices := test.GenerateRandomNewDevices(1) - - s.mockDeviceRepository.On("Create", newDevices[0]).Return(&model.Device{}, nil) - _, err := mutator.CreateDevice(s.ctx, newDevices[0]) - assert.Nil(s.T(), err) - - s.mockDeviceRepository.AssertCalled(s.T(), "Create", newDevices[0]) - - s.mockDeviceRepository.AssertExpectations(s.T()) -} - -func (s *DeviceGraphQLSuite) TestGetDevices() { - queryResolver := s.resolver.Query() - - s.mockDeviceRepository.On("GetAll").Return([]*model.Device{}, nil) - _, err := queryResolver.Devices(s.ctx) - assert.Nil(s.T(), err) - - s.mockDeviceRepository.AssertCalled(s.T(), "GetAll") - - s.mockDeviceRepository.AssertExpectations(s.T()) -} - -func (s *DeviceGraphQLSuite) TestDeleteDevice() { - mutator := s.resolver.Mutation() - - randomUUID := uuid.New().String() - - s.mockDeviceRepository.On("Delete", randomUUID).Return(&model.Device{}, nil) - _, err := mutator.DeleteDevice(s.ctx, randomUUID) - assert.Nil(s.T(), err) - - s.mockDeviceRepository.AssertCalled(s.T(), "Delete", randomUUID) - - s.mockDeviceRepository.AssertExpectations(s.T()) -} - -func (s *DeviceGraphQLSuite) TestUpdateDevice() { - mutator := s.resolver.Mutation() - tmpName := "McTesterson" - updateInput := model.UpdateDevice{ - ID: "uuid.string", - Name: &tmpName, - } - - s.mockDeviceRepository.On("Update", updateInput).Return(nil) - _, err := mutator.UpdateDevice(s.ctx, updateInput) - assert.Nil(s.T(), err) - - s.mockDeviceRepository.AssertCalled(s.T(), "Update", updateInput) - - s.mockDeviceRepository.AssertExpectations(s.T()) -} - -// In order for 'go test' to run this suite, we need to create -// a normal test function and pass our suite to suite.Run. -func TestDeviceGraphQLTestSuite(t *testing.T) { - suite.Run(t, new(DeviceGraphQLSuite)) -} diff --git a/graph/endpoint.resolvers.go b/graph/endpoint.resolvers.go deleted file mode 100644 index 944af815..00000000 --- a/graph/endpoint.resolvers.go +++ /dev/null @@ -1,46 +0,0 @@ -package graph - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - - generated1 "github.com/rna-vt/devicecommander/graph/generated" - "github.com/rna-vt/devicecommander/graph/model" -) - -func (r *endpointResolver) ID(ctx context.Context, obj *model.Endpoint) (string, error) { - return obj.ID.String(), nil -} - -func (r *endpointResolver) DeviceID(ctx context.Context, obj *model.Endpoint) (string, error) { - return obj.DeviceID.String(), nil -} - -func (r *parameterResolver) ID(ctx context.Context, obj *model.Parameter) (string, error) { - return obj.ID.String(), nil -} - -func (r *parameterResolver) EndpointID(ctx context.Context, obj *model.Parameter) (string, error) { - return obj.EndpointID.String(), nil -} - -func (r *queryResolver) Endpoints(ctx context.Context) ([]*model.Endpoint, error) { - endpoints, err := r.EndpointRepository.GetAll() - if err != nil { - return endpoints, err - } - return endpoints, nil -} - -// Endpoint returns generated1.EndpointResolver implementation. -func (r *Resolver) Endpoint() generated1.EndpointResolver { return &endpointResolver{r} } - -// Parameter returns generated1.ParameterResolver implementation. -func (r *Resolver) Parameter() generated1.ParameterResolver { return ¶meterResolver{r} } - -type ( - endpointResolver struct{ *Resolver } - parameterResolver struct{ *Resolver } -) diff --git a/graph/generated/generated.go b/graph/generated/generated.go deleted file mode 100644 index 7cac64f9..00000000 --- a/graph/generated/generated.go +++ /dev/null @@ -1,5278 +0,0 @@ -// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. - -package generated - -import ( - "bytes" - "context" - "errors" - "strconv" - "sync" - "sync/atomic" - - "github.com/99designs/gqlgen/graphql" - "github.com/99designs/gqlgen/graphql/introspection" - "github.com/rna-vt/devicecommander/graph/model" - gqlparser "github.com/vektah/gqlparser/v2" - "github.com/vektah/gqlparser/v2/ast" -) - -// region ************************** generated!.gotpl ************************** - -// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. -func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { - return &executableSchema{ - resolvers: cfg.Resolvers, - directives: cfg.Directives, - complexity: cfg.Complexity, - } -} - -type Config struct { - Resolvers ResolverRoot - Directives DirectiveRoot - Complexity ComplexityRoot -} - -type ResolverRoot interface { - Device() DeviceResolver - Endpoint() EndpointResolver - Mutation() MutationResolver - Parameter() ParameterResolver - Query() QueryResolver -} - -type DirectiveRoot struct { -} - -type ComplexityRoot struct { - Device struct { - Active func(childComplexity int) int - Description func(childComplexity int) int - Host func(childComplexity int) int - ID func(childComplexity int) int - MAC func(childComplexity int) int - Name func(childComplexity int) int - Port func(childComplexity int) int - } - - Endpoint struct { - Description func(childComplexity int) int - DeviceID func(childComplexity int) int - ID func(childComplexity int) int - Method func(childComplexity int) int - Parameters func(childComplexity int) int - Type func(childComplexity int) int - } - - Mutation struct { - CreateDevice func(childComplexity int, input model.NewDevice) int - DeleteDevice func(childComplexity int, id string) int - UpdateDevice func(childComplexity int, input model.UpdateDevice) int - } - - NewEndpoint struct { - Description func(childComplexity int) int - DeviceID func(childComplexity int) int - Method func(childComplexity int) int - Type func(childComplexity int) int - } - - NewParameter struct { - Description func(childComplexity int) int - EndpointID func(childComplexity int) int - Name func(childComplexity int) int - Type func(childComplexity int) int - } - - Parameter struct { - Description func(childComplexity int) int - EndpointID func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - Type func(childComplexity int) int - } - - Query struct { - Devices func(childComplexity int) int - Endpoints func(childComplexity int) int - } - - UpdateEndpoint struct { - Description func(childComplexity int) int - DeviceID func(childComplexity int) int - ID func(childComplexity int) int - Method func(childComplexity int) int - Type func(childComplexity int) int - } - - UpdateParameter struct { - Description func(childComplexity int) int - EndpointID func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - Type func(childComplexity int) int - } -} - -type DeviceResolver interface { - ID(ctx context.Context, obj *model.Device) (string, error) -} -type EndpointResolver interface { - ID(ctx context.Context, obj *model.Endpoint) (string, error) - DeviceID(ctx context.Context, obj *model.Endpoint) (string, error) -} -type MutationResolver interface { - CreateDevice(ctx context.Context, input model.NewDevice) (*model.Device, error) - UpdateDevice(ctx context.Context, input model.UpdateDevice) (string, error) - DeleteDevice(ctx context.Context, id string) (*model.Device, error) -} -type ParameterResolver interface { - ID(ctx context.Context, obj *model.Parameter) (string, error) - EndpointID(ctx context.Context, obj *model.Parameter) (string, error) -} -type QueryResolver interface { - Devices(ctx context.Context) ([]*model.Device, error) - Endpoints(ctx context.Context) ([]*model.Endpoint, error) -} - -type executableSchema struct { - resolvers ResolverRoot - directives DirectiveRoot - complexity ComplexityRoot -} - -func (e *executableSchema) Schema() *ast.Schema { - return parsedSchema -} - -func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { - ec := executionContext{nil, e} - _ = ec - switch typeName + "." + field { - - case "Device.Active": - if e.complexity.Device.Active == nil { - break - } - - return e.complexity.Device.Active(childComplexity), true - - case "Device.Description": - if e.complexity.Device.Description == nil { - break - } - - return e.complexity.Device.Description(childComplexity), true - - case "Device.Host": - if e.complexity.Device.Host == nil { - break - } - - return e.complexity.Device.Host(childComplexity), true - - case "Device.ID": - if e.complexity.Device.ID == nil { - break - } - - return e.complexity.Device.ID(childComplexity), true - - case "Device.MAC": - if e.complexity.Device.MAC == nil { - break - } - - return e.complexity.Device.MAC(childComplexity), true - - case "Device.Name": - if e.complexity.Device.Name == nil { - break - } - - return e.complexity.Device.Name(childComplexity), true - - case "Device.Port": - if e.complexity.Device.Port == nil { - break - } - - return e.complexity.Device.Port(childComplexity), true - - case "Endpoint.Description": - if e.complexity.Endpoint.Description == nil { - break - } - - return e.complexity.Endpoint.Description(childComplexity), true - - case "Endpoint.DeviceID": - if e.complexity.Endpoint.DeviceID == nil { - break - } - - return e.complexity.Endpoint.DeviceID(childComplexity), true - - case "Endpoint.ID": - if e.complexity.Endpoint.ID == nil { - break - } - - return e.complexity.Endpoint.ID(childComplexity), true - - case "Endpoint.Method": - if e.complexity.Endpoint.Method == nil { - break - } - - return e.complexity.Endpoint.Method(childComplexity), true - - case "Endpoint.Parameters": - if e.complexity.Endpoint.Parameters == nil { - break - } - - return e.complexity.Endpoint.Parameters(childComplexity), true - - case "Endpoint.Type": - if e.complexity.Endpoint.Type == nil { - break - } - - return e.complexity.Endpoint.Type(childComplexity), true - - case "Mutation.createDevice": - if e.complexity.Mutation.CreateDevice == nil { - break - } - - args, err := ec.field_Mutation_createDevice_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.CreateDevice(childComplexity, args["input"].(model.NewDevice)), true - - case "Mutation.deleteDevice": - if e.complexity.Mutation.DeleteDevice == nil { - break - } - - args, err := ec.field_Mutation_deleteDevice_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.DeleteDevice(childComplexity, args["id"].(string)), true - - case "Mutation.updateDevice": - if e.complexity.Mutation.UpdateDevice == nil { - break - } - - args, err := ec.field_Mutation_updateDevice_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.UpdateDevice(childComplexity, args["input"].(model.UpdateDevice)), true - - case "NewEndpoint.Description": - if e.complexity.NewEndpoint.Description == nil { - break - } - - return e.complexity.NewEndpoint.Description(childComplexity), true - - case "NewEndpoint.DeviceID": - if e.complexity.NewEndpoint.DeviceID == nil { - break - } - - return e.complexity.NewEndpoint.DeviceID(childComplexity), true - - case "NewEndpoint.Method": - if e.complexity.NewEndpoint.Method == nil { - break - } - - return e.complexity.NewEndpoint.Method(childComplexity), true - - case "NewEndpoint.Type": - if e.complexity.NewEndpoint.Type == nil { - break - } - - return e.complexity.NewEndpoint.Type(childComplexity), true - - case "NewParameter.Description": - if e.complexity.NewParameter.Description == nil { - break - } - - return e.complexity.NewParameter.Description(childComplexity), true - - case "NewParameter.EndpointID": - if e.complexity.NewParameter.EndpointID == nil { - break - } - - return e.complexity.NewParameter.EndpointID(childComplexity), true - - case "NewParameter.Name": - if e.complexity.NewParameter.Name == nil { - break - } - - return e.complexity.NewParameter.Name(childComplexity), true - - case "NewParameter.Type": - if e.complexity.NewParameter.Type == nil { - break - } - - return e.complexity.NewParameter.Type(childComplexity), true - - case "Parameter.Description": - if e.complexity.Parameter.Description == nil { - break - } - - return e.complexity.Parameter.Description(childComplexity), true - - case "Parameter.EndpointID": - if e.complexity.Parameter.EndpointID == nil { - break - } - - return e.complexity.Parameter.EndpointID(childComplexity), true - - case "Parameter.ID": - if e.complexity.Parameter.ID == nil { - break - } - - return e.complexity.Parameter.ID(childComplexity), true - - case "Parameter.Name": - if e.complexity.Parameter.Name == nil { - break - } - - return e.complexity.Parameter.Name(childComplexity), true - - case "Parameter.Type": - if e.complexity.Parameter.Type == nil { - break - } - - return e.complexity.Parameter.Type(childComplexity), true - - case "Query.devices": - if e.complexity.Query.Devices == nil { - break - } - - return e.complexity.Query.Devices(childComplexity), true - - case "Query.endpoints": - if e.complexity.Query.Endpoints == nil { - break - } - - return e.complexity.Query.Endpoints(childComplexity), true - - case "UpdateEndpoint.Description": - if e.complexity.UpdateEndpoint.Description == nil { - break - } - - return e.complexity.UpdateEndpoint.Description(childComplexity), true - - case "UpdateEndpoint.DeviceID": - if e.complexity.UpdateEndpoint.DeviceID == nil { - break - } - - return e.complexity.UpdateEndpoint.DeviceID(childComplexity), true - - case "UpdateEndpoint.ID": - if e.complexity.UpdateEndpoint.ID == nil { - break - } - - return e.complexity.UpdateEndpoint.ID(childComplexity), true - - case "UpdateEndpoint.Method": - if e.complexity.UpdateEndpoint.Method == nil { - break - } - - return e.complexity.UpdateEndpoint.Method(childComplexity), true - - case "UpdateEndpoint.Type": - if e.complexity.UpdateEndpoint.Type == nil { - break - } - - return e.complexity.UpdateEndpoint.Type(childComplexity), true - - case "UpdateParameter.Description": - if e.complexity.UpdateParameter.Description == nil { - break - } - - return e.complexity.UpdateParameter.Description(childComplexity), true - - case "UpdateParameter.EndpointID": - if e.complexity.UpdateParameter.EndpointID == nil { - break - } - - return e.complexity.UpdateParameter.EndpointID(childComplexity), true - - case "UpdateParameter.ID": - if e.complexity.UpdateParameter.ID == nil { - break - } - - return e.complexity.UpdateParameter.ID(childComplexity), true - - case "UpdateParameter.Name": - if e.complexity.UpdateParameter.Name == nil { - break - } - - return e.complexity.UpdateParameter.Name(childComplexity), true - - case "UpdateParameter.Type": - if e.complexity.UpdateParameter.Type == nil { - break - } - - return e.complexity.UpdateParameter.Type(childComplexity), true - - } - return 0, false -} - -func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { - rc := graphql.GetOperationContext(ctx) - ec := executionContext{rc, e} - first := true - - switch rc.Operation.Operation { - case ast.Query: - return func(ctx context.Context) *graphql.Response { - if !first { - return nil - } - first = false - data := ec._Query(ctx, rc.Operation.SelectionSet) - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - case ast.Mutation: - return func(ctx context.Context) *graphql.Response { - if !first { - return nil - } - first = false - data := ec._Mutation(ctx, rc.Operation.SelectionSet) - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - - default: - return graphql.OneShot(graphql.ErrorResponse(ctx, "unsupported GraphQL operation")) - } -} - -type executionContext struct { - *graphql.OperationContext - *executableSchema -} - -func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapSchema(parsedSchema), nil -} - -func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]), nil -} - -var sources = []*ast.Source{ - {Name: "graph/schemas/device.graphqls", Input: `type Device { - ID: String! - MAC: String - Name: String - Description: String - Host: String - Port: Int - Active: Boolean -} - -input NewDevice { - MAC: String - Name: String - Description: String - Host: String! - Port: Int! - Active: Boolean -} - -input UpdateDevice { - ID: String! - MAC: String - Name: String - Description: String - Host: String - Port: Int - Active: Boolean -} - -extend type Query { - devices: [Device!]! -} - -extend type Mutation { - createDevice(input: NewDevice!): Device! - updateDevice(input: UpdateDevice!): String! - deleteDevice(id: String!): Device! -} -`, BuiltIn: false}, - {Name: "graph/schemas/endpoint.graphqls", Input: `type Endpoint { - ID: String! - DeviceID: String! - Method: String! - Type: String! - Description: String - Parameters: [Parameter]! -} - -type NewEndpoint { - DeviceID: String! - Method: String! - Type: String! - Description: String -} - -type UpdateEndpoint { - ID: String! - DeviceID: String - Method: String - Type: String - Description: String -} - -type Parameter { - ID: String! - EndpointID: String! - Name: String! - Description: String - Type: String! -} - -type NewParameter { - EndpointID: String! - Name: String! - Description: String - Type: String! -} - -type UpdateParameter { - ID: String! - EndpointID: String - Name: String - Description: String - Type: String -} - -extend type Query { - endpoints: [Endpoint!]! -} -`, BuiltIn: false}, -} -var parsedSchema = gqlparser.MustLoadSchema(sources...) - -// endregion ************************** generated!.gotpl ************************** - -// region ***************************** args.gotpl ***************************** - -func (ec *executionContext) field_Mutation_createDevice_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.NewDevice - if tmp, ok := rawArgs["input"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("input")) - arg0, err = ec.unmarshalNNewDevice2githubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐNewDevice(ctx, tmp) - if err != nil { - return nil, err - } - } - args["input"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_deleteDevice_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_updateDevice_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.UpdateDevice - if tmp, ok := rawArgs["input"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("input")) - arg0, err = ec.unmarshalNUpdateDevice2githubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐUpdateDevice(ctx, tmp) - if err != nil { - return nil, err - } - } - args["input"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["name"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["name"] = arg0 - return args, nil -} - -func (ec *executionContext) field___Field_args_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *bool - if tmp, ok := rawArgs["includeDeprecated"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) - arg0, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["includeDeprecated"] = arg0 - return args, nil -} - -func (ec *executionContext) field___Type_enumValues_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 bool - if tmp, ok := rawArgs["includeDeprecated"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) - arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["includeDeprecated"] = arg0 - return args, nil -} - -func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 bool - if tmp, ok := rawArgs["includeDeprecated"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) - arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["includeDeprecated"] = arg0 - return args, nil -} - -// endregion ***************************** args.gotpl ***************************** - -// region ************************** directives.gotpl ************************** - -// endregion ************************** directives.gotpl ************************** - -// region **************************** field.gotpl ***************************** - -func (ec *executionContext) _Device_ID(ctx context.Context, field graphql.CollectedField, obj *model.Device) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Device", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Device().ID(rctx, obj) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Device_MAC(ctx context.Context, field graphql.CollectedField, obj *model.Device) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Device", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MAC, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Device_Name(ctx context.Context, field graphql.CollectedField, obj *model.Device) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Device", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Device_Description(ctx context.Context, field graphql.CollectedField, obj *model.Device) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Device", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Device_Host(ctx context.Context, field graphql.CollectedField, obj *model.Device) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Device", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Host, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Device_Port(ctx context.Context, field graphql.CollectedField, obj *model.Device) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Device", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Port, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalOInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) _Device_Active(ctx context.Context, field graphql.CollectedField, obj *model.Device) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Device", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Active, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalOBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) _Endpoint_ID(ctx context.Context, field graphql.CollectedField, obj *model.Endpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Endpoint", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Endpoint().ID(rctx, obj) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Endpoint_DeviceID(ctx context.Context, field graphql.CollectedField, obj *model.Endpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Endpoint", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Endpoint().DeviceID(rctx, obj) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Endpoint_Method(ctx context.Context, field graphql.CollectedField, obj *model.Endpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Endpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Method, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Endpoint_Type(ctx context.Context, field graphql.CollectedField, obj *model.Endpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Endpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Endpoint_Description(ctx context.Context, field graphql.CollectedField, obj *model.Endpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Endpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _Endpoint_Parameters(ctx context.Context, field graphql.CollectedField, obj *model.Endpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Endpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Parameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]model.Parameter) - fc.Result = res - return ec.marshalNParameter2ᚕgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐParameter(ctx, field.Selections, res) -} - -func (ec *executionContext) _Mutation_createDevice(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Mutation", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field_Mutation_createDevice_args(ctx, rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - fc.Args = args - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CreateDevice(rctx, args["input"].(model.NewDevice)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.Device) - fc.Result = res - return ec.marshalNDevice2ᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐDevice(ctx, field.Selections, res) -} - -func (ec *executionContext) _Mutation_updateDevice(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Mutation", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field_Mutation_updateDevice_args(ctx, rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - fc.Args = args - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().UpdateDevice(rctx, args["input"].(model.UpdateDevice)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Mutation_deleteDevice(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Mutation", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field_Mutation_deleteDevice_args(ctx, rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - fc.Args = args - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().DeleteDevice(rctx, args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.Device) - fc.Result = res - return ec.marshalNDevice2ᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐDevice(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewEndpoint_DeviceID(ctx context.Context, field graphql.CollectedField, obj *model.NewEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeviceID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewEndpoint_Method(ctx context.Context, field graphql.CollectedField, obj *model.NewEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Method, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewEndpoint_Type(ctx context.Context, field graphql.CollectedField, obj *model.NewEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewEndpoint_Description(ctx context.Context, field graphql.CollectedField, obj *model.NewEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewParameter_EndpointID(ctx context.Context, field graphql.CollectedField, obj *model.NewParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EndpointID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewParameter_Name(ctx context.Context, field graphql.CollectedField, obj *model.NewParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewParameter_Description(ctx context.Context, field graphql.CollectedField, obj *model.NewParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _NewParameter_Type(ctx context.Context, field graphql.CollectedField, obj *model.NewParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "NewParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Parameter_ID(ctx context.Context, field graphql.CollectedField, obj *model.Parameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Parameter", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Parameter().ID(rctx, obj) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Parameter_EndpointID(ctx context.Context, field graphql.CollectedField, obj *model.Parameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Parameter", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Parameter().EndpointID(rctx, obj) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Parameter_Name(ctx context.Context, field graphql.CollectedField, obj *model.Parameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Parameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Parameter_Description(ctx context.Context, field graphql.CollectedField, obj *model.Parameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Parameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _Parameter_Type(ctx context.Context, field graphql.CollectedField, obj *model.Parameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Parameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Query_devices(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Query", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().Devices(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.Device) - fc.Result = res - return ec.marshalNDevice2ᚕᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐDeviceᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) _Query_endpoints(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Query", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: true, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().Endpoints(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.Endpoint) - fc.Result = res - return ec.marshalNEndpoint2ᚕᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐEndpointᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Query", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field_Query___type_args(ctx, rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - fc.Args = args - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.introspectType(args["name"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Query", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.introspectSchema() - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Schema) - fc.Result = res - return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateEndpoint_ID(ctx context.Context, field graphql.CollectedField, obj *model.UpdateEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateEndpoint_DeviceID(ctx context.Context, field graphql.CollectedField, obj *model.UpdateEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeviceID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateEndpoint_Method(ctx context.Context, field graphql.CollectedField, obj *model.UpdateEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Method, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateEndpoint_Type(ctx context.Context, field graphql.CollectedField, obj *model.UpdateEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateEndpoint_Description(ctx context.Context, field graphql.CollectedField, obj *model.UpdateEndpoint) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateEndpoint", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateParameter_ID(ctx context.Context, field graphql.CollectedField, obj *model.UpdateParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateParameter_EndpointID(ctx context.Context, field graphql.CollectedField, obj *model.UpdateParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EndpointID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateParameter_Name(ctx context.Context, field graphql.CollectedField, obj *model.UpdateParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateParameter_Description(ctx context.Context, field graphql.CollectedField, obj *model.UpdateParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _UpdateParameter_Type(ctx context.Context, field graphql.CollectedField, obj *model.UpdateParameter) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "UpdateParameter", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Directive", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Directive_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Directive", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Directive_locations(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Directive", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Locations, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalN__DirectiveLocation2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Directive_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Directive", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Args, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Directive", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsRepeatable, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) ___EnumValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___EnumValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsDeprecated(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) ___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeprecationReason(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Field_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Field", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Field_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Field", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Field_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Field", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field___Field_args_args(ctx, rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - fc.Args = args - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Args, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Field_type(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Field", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Field_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Field", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsDeprecated(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Field_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Field", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeprecationReason(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) ___InputValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___InputValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___InputValue_type(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) ___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultValue, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Schema_types(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Schema", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Types(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Schema_queryType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Schema", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.QueryType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Schema_mutationType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Schema", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MutationType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Schema", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubscriptionType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Schema_directives(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Schema", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Directives(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.Directive) - fc.Result = res - return ec.marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_kind(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Kind(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalN__TypeKind2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalOString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_fields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field___Type_fields_args(ctx, rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - fc.Args = args - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Fields(args["includeDeprecated"].(bool)), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Field) - fc.Result = res - return ec.marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_interfaces(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Interfaces(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_possibleTypes(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PossibleTypes(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_enumValues(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field___Type_enumValues_args(ctx, rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - fc.Args = args - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EnumValues(args["includeDeprecated"].(bool)), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.EnumValue) - fc.Result = res - return ec.marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_inputFields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.InputFields(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "__Type", - Field: field, - Args: nil, - IsMethod: true, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.OfType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -// endregion **************************** field.gotpl ***************************** - -// region **************************** input.gotpl ***************************** - -func (ec *executionContext) unmarshalInputNewDevice(ctx context.Context, obj interface{}) (model.NewDevice, error) { - var it model.NewDevice - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - for k, v := range asMap { - switch k { - case "MAC": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("MAC")) - it.Mac, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "Name": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Name")) - it.Name, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "Description": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Description")) - it.Description, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "Host": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Host")) - it.Host, err = ec.unmarshalNString2string(ctx, v) - if err != nil { - return it, err - } - case "Port": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Port")) - it.Port, err = ec.unmarshalNInt2int(ctx, v) - if err != nil { - return it, err - } - case "Active": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Active")) - it.Active, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputUpdateDevice(ctx context.Context, obj interface{}) (model.UpdateDevice, error) { - var it model.UpdateDevice - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - for k, v := range asMap { - switch k { - case "ID": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("ID")) - it.ID, err = ec.unmarshalNString2string(ctx, v) - if err != nil { - return it, err - } - case "MAC": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("MAC")) - it.Mac, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "Name": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Name")) - it.Name, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "Description": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Description")) - it.Description, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "Host": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Host")) - it.Host, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "Port": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Port")) - it.Port, err = ec.unmarshalOInt2ᚖint(ctx, v) - if err != nil { - return it, err - } - case "Active": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("Active")) - it.Active, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -// endregion **************************** input.gotpl ***************************** - -// region ************************** interface.gotpl *************************** - -// endregion ************************** interface.gotpl *************************** - -// region **************************** object.gotpl **************************** - -var deviceImplementors = []string{"Device"} - -func (ec *executionContext) _Device(ctx context.Context, sel ast.SelectionSet, obj *model.Device) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, deviceImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Device") - case "ID": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Device_ID(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - out.Concurrently(i, func() graphql.Marshaler { - return innerFunc(ctx) - - }) - case "MAC": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Device_MAC(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Device_Name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Device_Description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Host": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Device_Host(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Port": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Device_Port(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Active": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Device_Active(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var endpointImplementors = []string{"Endpoint"} - -func (ec *executionContext) _Endpoint(ctx context.Context, sel ast.SelectionSet, obj *model.Endpoint) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, endpointImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Endpoint") - case "ID": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Endpoint_ID(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - out.Concurrently(i, func() graphql.Marshaler { - return innerFunc(ctx) - - }) - case "DeviceID": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Endpoint_DeviceID(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - out.Concurrently(i, func() graphql.Marshaler { - return innerFunc(ctx) - - }) - case "Method": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Endpoint_Method(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - case "Type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Endpoint_Type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - case "Description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Endpoint_Description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Parameters": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Endpoint_Parameters(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var mutationImplementors = []string{"Mutation"} - -func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, mutationImplementors) - ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ - Object: "Mutation", - }) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ - Object: field.Name, - Field: field, - }) - - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Mutation") - case "createDevice": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_createDevice(ctx, field) - } - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, innerFunc) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "updateDevice": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_updateDevice(ctx, field) - } - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, innerFunc) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "deleteDevice": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_deleteDevice(ctx, field) - } - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, innerFunc) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var newEndpointImplementors = []string{"NewEndpoint"} - -func (ec *executionContext) _NewEndpoint(ctx context.Context, sel ast.SelectionSet, obj *model.NewEndpoint) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, newEndpointImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("NewEndpoint") - case "DeviceID": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewEndpoint_DeviceID(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "Method": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewEndpoint_Method(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "Type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewEndpoint_Type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "Description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewEndpoint_Description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var newParameterImplementors = []string{"NewParameter"} - -func (ec *executionContext) _NewParameter(ctx context.Context, sel ast.SelectionSet, obj *model.NewParameter) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, newParameterImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("NewParameter") - case "EndpointID": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewParameter_EndpointID(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "Name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewParameter_Name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "Description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewParameter_Description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._NewParameter_Type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var parameterImplementors = []string{"Parameter"} - -func (ec *executionContext) _Parameter(ctx context.Context, sel ast.SelectionSet, obj *model.Parameter) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, parameterImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Parameter") - case "ID": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Parameter_ID(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - out.Concurrently(i, func() graphql.Marshaler { - return innerFunc(ctx) - - }) - case "EndpointID": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Parameter_EndpointID(ctx, field, obj) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - out.Concurrently(i, func() graphql.Marshaler { - return innerFunc(ctx) - - }) - case "Name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Parameter_Name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - case "Description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Parameter_Description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Parameter_Type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var queryImplementors = []string{"Query"} - -func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, queryImplementors) - ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ - Object: "Query", - }) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ - Object: field.Name, - Field: field, - }) - - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Query") - case "devices": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_devices(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "endpoints": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_endpoints(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "__type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Query___type(ctx, field) - } - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, innerFunc) - - case "__schema": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._Query___schema(ctx, field) - } - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, innerFunc) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var updateEndpointImplementors = []string{"UpdateEndpoint"} - -func (ec *executionContext) _UpdateEndpoint(ctx context.Context, sel ast.SelectionSet, obj *model.UpdateEndpoint) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, updateEndpointImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("UpdateEndpoint") - case "ID": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateEndpoint_ID(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "DeviceID": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateEndpoint_DeviceID(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Method": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateEndpoint_Method(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateEndpoint_Type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateEndpoint_Description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var updateParameterImplementors = []string{"UpdateParameter"} - -func (ec *executionContext) _UpdateParameter(ctx context.Context, sel ast.SelectionSet, obj *model.UpdateParameter) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, updateParameterImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("UpdateParameter") - case "ID": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateParameter_ID(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "EndpointID": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateParameter_EndpointID(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateParameter_Name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateParameter_Description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "Type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec._UpdateParameter_Type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __DirectiveImplementors = []string{"__Directive"} - -func (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __DirectiveImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Directive") - case "name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Directive_name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Directive_description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "locations": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Directive_locations(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "args": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Directive_args(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "isRepeatable": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Directive_isRepeatable(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __EnumValueImplementors = []string{"__EnumValue"} - -func (ec *executionContext) ___EnumValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.EnumValue) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __EnumValueImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__EnumValue") - case "name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___EnumValue_name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___EnumValue_description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "isDeprecated": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___EnumValue_isDeprecated(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "deprecationReason": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___EnumValue_deprecationReason(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __FieldImplementors = []string{"__Field"} - -func (ec *executionContext) ___Field(ctx context.Context, sel ast.SelectionSet, obj *introspection.Field) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __FieldImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Field") - case "name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Field_name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Field_description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "args": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Field_args(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Field_type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "isDeprecated": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Field_isDeprecated(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "deprecationReason": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Field_deprecationReason(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __InputValueImplementors = []string{"__InputValue"} - -func (ec *executionContext) ___InputValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.InputValue) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __InputValueImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__InputValue") - case "name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___InputValue_name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___InputValue_description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "type": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___InputValue_type(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "defaultValue": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___InputValue_defaultValue(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __SchemaImplementors = []string{"__Schema"} - -func (ec *executionContext) ___Schema(ctx context.Context, sel ast.SelectionSet, obj *introspection.Schema) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __SchemaImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Schema") - case "types": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Schema_types(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "queryType": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Schema_queryType(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "mutationType": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Schema_mutationType(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "subscriptionType": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Schema_subscriptionType(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "directives": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Schema_directives(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __TypeImplementors = []string{"__Type"} - -func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, obj *introspection.Type) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __TypeImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Type") - case "kind": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_kind(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_name(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "description": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_description(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "fields": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_fields(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "interfaces": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_interfaces(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "possibleTypes": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_possibleTypes(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "enumValues": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_enumValues(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "inputFields": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_inputFields(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - case "ofType": - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - return ec.___Type_ofType(ctx, field, obj) - } - - out.Values[i] = innerFunc(ctx) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -// endregion **************************** object.gotpl **************************** - -// region ***************************** type.gotpl ***************************** - -func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v interface{}) (bool, error) { - res, err := graphql.UnmarshalBoolean(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { - res := graphql.MarshalBoolean(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - } - return res -} - -func (ec *executionContext) marshalNDevice2githubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐDevice(ctx context.Context, sel ast.SelectionSet, v model.Device) graphql.Marshaler { - return ec._Device(ctx, sel, &v) -} - -func (ec *executionContext) marshalNDevice2ᚕᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐDeviceᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.Device) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNDevice2ᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐDevice(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNDevice2ᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐDevice(ctx context.Context, sel ast.SelectionSet, v *model.Device) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - return ec._Device(ctx, sel, v) -} - -func (ec *executionContext) marshalNEndpoint2ᚕᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐEndpointᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.Endpoint) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNEndpoint2ᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐEndpoint(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNEndpoint2ᚖgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐEndpoint(ctx context.Context, sel ast.SelectionSet, v *model.Endpoint) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - return ec._Endpoint(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNInt2int(ctx context.Context, v interface{}) (int, error) { - res, err := graphql.UnmarshalInt(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { - res := graphql.MarshalInt(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - } - return res -} - -func (ec *executionContext) unmarshalNNewDevice2githubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐNewDevice(ctx context.Context, v interface{}) (model.NewDevice, error) { - res, err := ec.unmarshalInputNewDevice(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNParameter2ᚕgithubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐParameter(ctx context.Context, sel ast.SelectionSet, v []model.Parameter) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOParameter2githubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐParameter(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) unmarshalNString2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalString(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalString(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - } - return res -} - -func (ec *executionContext) unmarshalNUpdateDevice2githubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐUpdateDevice(ctx context.Context, v interface{}) (model.UpdateDevice, error) { - res, err := ec.unmarshalInputUpdateDevice(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx context.Context, sel ast.SelectionSet, v introspection.Directive) graphql.Marshaler { - return ec.___Directive(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Directive) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalN__DirectiveLocation2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalString(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalN__DirectiveLocation2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalString(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - } - return res -} - -func (ec *executionContext) unmarshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalN__DirectiveLocation2string(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__DirectiveLocation2string(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx context.Context, sel ast.SelectionSet, v introspection.EnumValue) graphql.Marshaler { - return ec.___EnumValue(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx context.Context, sel ast.SelectionSet, v introspection.Field) graphql.Marshaler { - return ec.___Field(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx context.Context, sel ast.SelectionSet, v introspection.InputValue) graphql.Marshaler { - return ec.___InputValue(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v introspection.Type) graphql.Marshaler { - return ec.___Type(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - return ec.___Type(ctx, sel, v) -} - -func (ec *executionContext) unmarshalN__TypeKind2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalString(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalString(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - } - return res -} - -func (ec *executionContext) unmarshalOBoolean2bool(ctx context.Context, v interface{}) (bool, error) { - res, err := graphql.UnmarshalBoolean(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { - res := graphql.MarshalBoolean(v) - return res -} - -func (ec *executionContext) unmarshalOBoolean2ᚖbool(ctx context.Context, v interface{}) (*bool, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalBoolean(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOBoolean2ᚖbool(ctx context.Context, sel ast.SelectionSet, v *bool) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalBoolean(*v) - return res -} - -func (ec *executionContext) unmarshalOInt2int(ctx context.Context, v interface{}) (int, error) { - res, err := graphql.UnmarshalInt(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { - res := graphql.MarshalInt(v) - return res -} - -func (ec *executionContext) unmarshalOInt2ᚖint(ctx context.Context, v interface{}) (*int, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalInt(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOInt2ᚖint(ctx context.Context, sel ast.SelectionSet, v *int) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalInt(*v) - return res -} - -func (ec *executionContext) marshalOParameter2githubᚗcomᚋrnaᚑvtᚋdevicecommanderᚋgraphᚋmodelᚐParameter(ctx context.Context, sel ast.SelectionSet, v model.Parameter) graphql.Marshaler { - return ec._Parameter(ctx, sel, &v) -} - -func (ec *executionContext) unmarshalOString2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalString(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalString(v) - return res -} - -func (ec *executionContext) unmarshalOString2ᚖstring(ctx context.Context, v interface{}) (*string, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalString(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOString2ᚖstring(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalString(*v) - return res -} - -func (ec *executionContext) marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.EnumValue) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Field) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx context.Context, sel ast.SelectionSet, v *introspection.Schema) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec.___Schema(ctx, sel, v) -} - -func (ec *executionContext) marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec.___Type(ctx, sel, v) -} - -// endregion ***************************** type.gotpl ***************************** diff --git a/graph/model/device.go b/graph/model/device.go deleted file mode 100644 index 3262525c..00000000 --- a/graph/model/device.go +++ /dev/null @@ -1,54 +0,0 @@ -package model - -import ( - "github.com/google/uuid" -) - -// Device -- a compliant physical component. -// -// ID -- the serial number of the connecting device -// Name - Optional Device Nickname -// Description - Optional text describing this device -// Host - Device Api Host -// Port - Device Api Port. Set to 443 for https -// -// swagger:model -type Device struct { - // the UUID for the device. - // - // required: true - // example: 705e4dcb-3ecd-24f3-3a35-3e926e4bded5 - ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` - - // the MAC address for this device. - // required: true - MAC string `json:"MAC" gorm:"unique" faker:"mac_address"` - - // the human readable name of the device. - // required: false - Name string `json:"Name"` - - // the description of the device. - // required: false - Description string `json:"Description"` - - // the host address of the device. - // required: true - Host string `json:"Host" faker:"ipv4"` - - // the active port of the device. - // required: true - Port int `json:"Port" faker:"boundary_start=49152, boundary_end=65535"` - - // the count of failed actions by the device. - // required: false - Failures int `json:"Failures" faker:"boundary_start=0, boundary_end=5"` - - // a flag representing the responsiveness of the device. - // required: false - Active bool `json:"Active"` - - // a list of endpoints available for quering on a device. - // required: false - Endpoints []Endpoint `json:"Endpoints" faker:"-"` -} diff --git a/graph/model/endpoint.go b/graph/model/endpoint.go deleted file mode 100644 index 562f4fc1..00000000 --- a/graph/model/endpoint.go +++ /dev/null @@ -1,21 +0,0 @@ -package model - -import "github.com/google/uuid" - -type Endpoint struct { - ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` - DeviceID uuid.UUID `json:"DeviceID" faker:"uuid_hyphenated"` - Method string `json:"Method"` - Type string `json:"Type" faker:"oneof: get, set"` - Description *string `json:"Description"` - Path *string `json:"Path"` - Parameters []Parameter `json:"Parameters,omitempty"` -} - -type Parameter struct { - ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` - EndpointID uuid.UUID `json:"EndpointID" faker:"uuid_hyphenated"` - Name string `json:"Name"` - Description *string `json:"Description"` - Type string `json:"Type" faker:"oneof: string, int, bool"` -} diff --git a/graph/model/models.go b/graph/model/models.go deleted file mode 100644 index dc281388..00000000 --- a/graph/model/models.go +++ /dev/null @@ -1,53 +0,0 @@ -package model - -// Device models. -type NewDevice struct { - Mac *string `json:"MAC" faker:"mac_address"` - Name *string `json:"Name"` - Description *string `json:"Description"` - Host string `json:"Host" faker:"ipv4"` - Port int `json:"Port" faker:"boundary_start=49152, boundary_end=65535"` - Active *bool `json:"Active"` -} - -type UpdateDevice struct { - ID string `json:"ID" faker:"uuid_hyphenated"` - Mac *string `json:"MAC" faker:"mac_address"` - Name *string `json:"Name"` - Description *string `json:"Description"` - Host *string `json:"Host" faker:"ipv4"` - Port *int `json:"Port" faker:"boundary_start=49152, boundary_end=65535"` - Active *bool `json:"Active"` -} - -// Endpoint models. -type NewEndpoint struct { - DeviceID string `json:"DeviceID" faker:"uuid_hyphenated"` - Method string `json:"Method"` - Type string `json:"Type" faker:"oneof: get, set"` - Description *string `json:"Description"` -} - -type UpdateEndpoint struct { - ID string `json:"ID" faker:"uuid_hyphenated"` - DeviceID *string `json:"DeviceID" faker:"uuid_hyphenated"` - Method *string `json:"Method"` - Type *string `json:"Type" faker:"oneof: get, set"` - Description *string `json:"Description"` -} - -// Parameter models. -type NewParameter struct { - EndpointID string `json:"EndpointID" faker:"uuid_hyphenated"` - Name string `json:"Name"` - Description *string `json:"Description"` - Type string `json:"Type" faker:"oneof: string, int, bool"` -} - -type UpdateParameter struct { - ID string `json:"ID" faker:"uuid_hyphenated"` - EndpointID *string `json:"EndpointID" faker:"uuid_hyphenated"` - Name *string `json:"Name"` - Description *string `json:"Description"` - Type *string `json:"Type" faker:"oneof: string, int, bool"` -} diff --git a/graph/resolver.go b/graph/resolver.go deleted file mode 100644 index c2d1d677..00000000 --- a/graph/resolver.go +++ /dev/null @@ -1,17 +0,0 @@ -package graph - -import ( - "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/endpoint" -) - -//go:generate go run github.com/99designs/gqlgen - -// This file will not be regenerated automatically. -// -// It serves as dependency injection for your app, add any dependencies you require here. - -type Resolver struct { - DeviceRepository device.Repository - EndpointRepository endpoint.Repository -} diff --git a/graph/schemas/device.graphqls b/graph/schemas/device.graphqls deleted file mode 100644 index cf7a7513..00000000 --- a/graph/schemas/device.graphqls +++ /dev/null @@ -1,38 +0,0 @@ -type Device { - ID: String! - MAC: String - Name: String - Description: String - Host: String - Port: Int - Active: Boolean -} - -input NewDevice { - MAC: String - Name: String - Description: String - Host: String! - Port: Int! - Active: Boolean -} - -input UpdateDevice { - ID: String! - MAC: String - Name: String - Description: String - Host: String - Port: Int - Active: Boolean -} - -extend type Query { - devices: [Device!]! -} - -extend type Mutation { - createDevice(input: NewDevice!): Device! - updateDevice(input: UpdateDevice!): String! - deleteDevice(id: String!): Device! -} diff --git a/graph/schemas/endpoint.graphqls b/graph/schemas/endpoint.graphqls deleted file mode 100644 index 62fde8a1..00000000 --- a/graph/schemas/endpoint.graphqls +++ /dev/null @@ -1,50 +0,0 @@ -type Endpoint { - ID: String! - DeviceID: String! - Method: String! - Type: String! - Description: String - Parameters: [Parameter]! -} - -type NewEndpoint { - DeviceID: String! - Method: String! - Type: String! - Description: String -} - -type UpdateEndpoint { - ID: String! - DeviceID: String - Method: String - Type: String - Description: String -} - -type Parameter { - ID: String! - EndpointID: String! - Name: String! - Description: String - Type: String! -} - -type NewParameter { - EndpointID: String! - Name: String! - Description: String - Type: String! -} - -type UpdateParameter { - ID: String! - EndpointID: String - Name: String - Description: String - Type: String -} - -extend type Query { - endpoints: [Endpoint!]! -} diff --git a/mocks/cluster/Cluster.go b/mocks/cluster/Cluster.go index b2b334a6..c799e07e 100644 --- a/mocks/cluster/Cluster.go +++ b/mocks/cluster/Cluster.go @@ -3,7 +3,7 @@ package mocks import ( - model "github.com/rna-vt/devicecommander/graph/model" + device "github.com/rna-vt/devicecommander/src/device" mock "github.com/stretchr/testify/mock" ) @@ -18,17 +18,24 @@ func (_m *Cluster) DeviceDiscovery(_a0 int) { } // HandleDiscoveredDevice provides a mock function with given fields: _a0 -func (_m *Cluster) HandleDiscoveredDevice(_a0 model.NewDevice) error { +func (_m *Cluster) HandleDiscoveredDevice(_a0 device.NewDeviceParams) (device.Device, error) { ret := _m.Called(_a0) - var r0 error - if rf, ok := ret.Get(0).(func(model.NewDevice) error); ok { + var r0 device.Device + if rf, ok := ret.Get(0).(func(device.NewDeviceParams) device.Device); ok { r0 = rf(_a0) } else { - r0 = ret.Error(0) + r0 = ret.Get(0).(device.Device) } - return r0 + var r1 error + if rf, ok := ret.Get(1).(func(device.NewDeviceParams) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 } // Name provides a mock function with given fields: diff --git a/mocks/device/Device.go b/mocks/device/BasicDevice.go similarity index 51% rename from mocks/device/Device.go rename to mocks/device/BasicDevice.go index d4f585c7..91cde9eb 100644 --- a/mocks/device/Device.go +++ b/mocks/device/BasicDevice.go @@ -3,61 +3,17 @@ package mocks import ( - io "io" - device "github.com/rna-vt/devicecommander/src/device" - mock "github.com/stretchr/testify/mock" - - model "github.com/rna-vt/devicecommander/graph/model" - - uuid "github.com/google/uuid" ) -// Device is an autogenerated mock type for the Device type -type Device struct { +// BasicDevice is an autogenerated mock type for the BasicDevice type +type BasicDevice struct { mock.Mock } -// ID provides a mock function with given fields: -func (_m *Device) ID() uuid.UUID { - ret := _m.Called() - - var r0 uuid.UUID - if rf, ok := ret.Get(0).(func() uuid.UUID); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(uuid.UUID) - } - } - - return r0 -} - -// NewDeviceFromRequestBody provides a mock function with given fields: body -func (_m *Device) NewDeviceFromRequestBody(body io.ReadCloser) (model.NewDevice, error) { - ret := _m.Called(body) - - var r0 model.NewDevice - if rf, ok := ret.Get(0).(func(io.ReadCloser) model.NewDevice); ok { - r0 = rf(body) - } else { - r0 = ret.Get(0).(model.NewDevice) - } - - var r1 error - if rf, ok := ret.Get(1).(func(io.ReadCloser) error); ok { - r1 = rf(body) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // ProcessHealthCheckResult provides a mock function with given fields: result -func (_m *Device) ProcessHealthCheckResult(result bool) int { +func (_m *BasicDevice) ProcessHealthCheckResult(result bool) int { ret := _m.Called(result) var r0 int @@ -71,7 +27,7 @@ func (_m *Device) ProcessHealthCheckResult(result bool) int { } // RunHealthCheck provides a mock function with given fields: client -func (_m *Device) RunHealthCheck(client device.Client) error { +func (_m *BasicDevice) RunHealthCheck(client device.Client) error { ret := _m.Called(client) var r0 error @@ -85,7 +41,7 @@ func (_m *Device) RunHealthCheck(client device.Client) error { } // URL provides a mock function with given fields: -func (_m *Device) URL() string { +func (_m *BasicDevice) URL() string { ret := _m.Called() var r0 string @@ -99,7 +55,7 @@ func (_m *Device) URL() string { } // Unresponsive provides a mock function with given fields: -func (_m *Device) Unresponsive() bool { +func (_m *BasicDevice) Unresponsive() bool { ret := _m.Called() var r0 bool @@ -113,7 +69,7 @@ func (_m *Device) Unresponsive() bool { } // protocol provides a mock function with given fields: -func (_m *Device) protocol() string { +func (_m *BasicDevice) protocol() string { ret := _m.Called() var r0 string diff --git a/mocks/device/Client.go b/mocks/device/Client.go index 6f6f4c3e..f5d38610 100644 --- a/mocks/device/Client.go +++ b/mocks/device/Client.go @@ -8,8 +8,6 @@ import ( device "github.com/rna-vt/devicecommander/src/device" mock "github.com/stretchr/testify/mock" - - model "github.com/rna-vt/devicecommander/graph/model" ) // Client is an autogenerated mock type for the Client type @@ -32,14 +30,14 @@ func (_m *Client) EvaluateHealthCheckResponse(resp *http.Response, d device.Devi } // EvaluateSpecificationResponse provides a mock function with given fields: _a0 -func (_m *Client) EvaluateSpecificationResponse(_a0 *http.Response) (model.Device, error) { +func (_m *Client) EvaluateSpecificationResponse(_a0 *http.Response) (device.Device, error) { ret := _m.Called(_a0) - var r0 model.Device - if rf, ok := ret.Get(0).(func(*http.Response) model.Device); ok { + var r0 device.Device + if rf, ok := ret.Get(0).(func(*http.Response) device.Device); ok { r0 = rf(_a0) } else { - r0 = ret.Get(0).(model.Device) + r0 = ret.Get(0).(device.Device) } var r1 error @@ -76,14 +74,14 @@ func (_m *Client) Health(_a0 device.Device) (*http.Response, error) { } // Info provides a mock function with given fields: _a0 -func (_m *Client) Info(_a0 device.Device) (model.NewDevice, error) { +func (_m *Client) Info(_a0 device.Device) (device.NewDeviceParams, error) { ret := _m.Called(_a0) - var r0 model.NewDevice - if rf, ok := ret.Get(0).(func(device.Device) model.NewDevice); ok { + var r0 device.NewDeviceParams + if rf, ok := ret.Get(0).(func(device.Device) device.NewDeviceParams); ok { r0 = rf(_a0) } else { - r0 = ret.Get(0).(model.NewDevice) + r0 = ret.Get(0).(device.NewDeviceParams) } var r1 error diff --git a/mocks/endpoint/Endpoint.go b/mocks/device/DeviceEndpoint.go similarity index 66% rename from mocks/endpoint/Endpoint.go rename to mocks/device/DeviceEndpoint.go index b2bcf256..6149e93c 100644 --- a/mocks/endpoint/Endpoint.go +++ b/mocks/device/DeviceEndpoint.go @@ -4,13 +4,13 @@ package mocks import mock "github.com/stretchr/testify/mock" -// Endpoint is an autogenerated mock type for the Endpoint type -type Endpoint struct { +// DeviceEndpoint is an autogenerated mock type for the DeviceEndpoint type +type DeviceEndpoint struct { mock.Mock } // Execute provides a mock function with given fields: _a0 -func (_m *Endpoint) Execute(_a0 map[string]interface{}) error { +func (_m *DeviceEndpoint) Execute(_a0 map[string]interface{}) error { ret := _m.Called(_a0) var r0 error diff --git a/mocks/device/EndpointRepository.go b/mocks/device/EndpointRepository.go new file mode 100644 index 00000000..ab16b5f6 --- /dev/null +++ b/mocks/device/EndpointRepository.go @@ -0,0 +1,119 @@ +// Code generated by mockery v2.9.4. DO NOT EDIT. + +package mocks + +import ( + device "github.com/rna-vt/devicecommander/src/device" + mock "github.com/stretchr/testify/mock" +) + +// EndpointRepository is an autogenerated mock type for the EndpointRepository type +type EndpointRepository struct { + mock.Mock +} + +// Create provides a mock function with given fields: _a0 +func (_m *EndpointRepository) Create(_a0 device.NewEndpointParams) (*device.Endpoint, error) { + ret := _m.Called(_a0) + + var r0 *device.Endpoint + if rf, ok := ret.Get(0).(func(device.NewEndpointParams) *device.Endpoint); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*device.Endpoint) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(device.NewEndpointParams) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Delete provides a mock function with given fields: _a0 +func (_m *EndpointRepository) Delete(_a0 string) (*device.Endpoint, error) { + ret := _m.Called(_a0) + + var r0 *device.Endpoint + if rf, ok := ret.Get(0).(func(string) *device.Endpoint); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*device.Endpoint) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Get provides a mock function with given fields: _a0 +func (_m *EndpointRepository) Get(_a0 device.Endpoint) ([]*device.Endpoint, error) { + ret := _m.Called(_a0) + + var r0 []*device.Endpoint + if rf, ok := ret.Get(0).(func(device.Endpoint) []*device.Endpoint); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*device.Endpoint) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(device.Endpoint) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetAll provides a mock function with given fields: +func (_m *EndpointRepository) GetAll() ([]*device.Endpoint, error) { + ret := _m.Called() + + var r0 []*device.Endpoint + if rf, ok := ret.Get(0).(func() []*device.Endpoint); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*device.Endpoint) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Update provides a mock function with given fields: _a0 +func (_m *EndpointRepository) Update(_a0 device.UpdateEndpointParams) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(device.UpdateEndpointParams) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} diff --git a/mocks/device/ParameterRepository.go b/mocks/device/ParameterRepository.go new file mode 100644 index 00000000..605f0f71 --- /dev/null +++ b/mocks/device/ParameterRepository.go @@ -0,0 +1,119 @@ +// Code generated by mockery v2.9.4. DO NOT EDIT. + +package mocks + +import ( + device "github.com/rna-vt/devicecommander/src/device" + mock "github.com/stretchr/testify/mock" +) + +// ParameterRepository is an autogenerated mock type for the ParameterRepository type +type ParameterRepository struct { + mock.Mock +} + +// Create provides a mock function with given fields: _a0 +func (_m *ParameterRepository) Create(_a0 device.NewParameterParams) (*device.Parameter, error) { + ret := _m.Called(_a0) + + var r0 *device.Parameter + if rf, ok := ret.Get(0).(func(device.NewParameterParams) *device.Parameter); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*device.Parameter) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(device.NewParameterParams) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Delete provides a mock function with given fields: _a0 +func (_m *ParameterRepository) Delete(_a0 string) (*device.Parameter, error) { + ret := _m.Called(_a0) + + var r0 *device.Parameter + if rf, ok := ret.Get(0).(func(string) *device.Parameter); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*device.Parameter) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(string) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Get provides a mock function with given fields: _a0 +func (_m *ParameterRepository) Get(_a0 device.Parameter) ([]*device.Parameter, error) { + ret := _m.Called(_a0) + + var r0 []*device.Parameter + if rf, ok := ret.Get(0).(func(device.Parameter) []*device.Parameter); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*device.Parameter) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(device.Parameter) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetAll provides a mock function with given fields: +func (_m *ParameterRepository) GetAll() ([]*device.Parameter, error) { + ret := _m.Called() + + var r0 []*device.Parameter + if rf, ok := ret.Get(0).(func() []*device.Parameter); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*device.Parameter) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Update provides a mock function with given fields: _a0 +func (_m *ParameterRepository) Update(_a0 device.UpdateParameterParams) error { + ret := _m.Called(_a0) + + var r0 error + if rf, ok := ret.Get(0).(func(device.UpdateParameterParams) error); ok { + r0 = rf(_a0) + } else { + r0 = ret.Error(0) + } + + return r0 +} diff --git a/mocks/device/Repository.go b/mocks/device/Repository.go index c9aacb1d..67a9e1a6 100644 --- a/mocks/device/Repository.go +++ b/mocks/device/Repository.go @@ -3,7 +3,7 @@ package mocks import ( - model "github.com/rna-vt/devicecommander/graph/model" + device "github.com/rna-vt/devicecommander/src/device" mock "github.com/stretchr/testify/mock" ) @@ -13,20 +13,20 @@ type Repository struct { } // Create provides a mock function with given fields: _a0 -func (_m *Repository) Create(_a0 model.NewDevice) (*model.Device, error) { +func (_m *Repository) Create(_a0 device.NewDeviceParams) (*device.Device, error) { ret := _m.Called(_a0) - var r0 *model.Device - if rf, ok := ret.Get(0).(func(model.NewDevice) *model.Device); ok { + var r0 *device.Device + if rf, ok := ret.Get(0).(func(device.NewDeviceParams) *device.Device); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Device) + r0 = ret.Get(0).(*device.Device) } } var r1 error - if rf, ok := ret.Get(1).(func(model.NewDevice) error); ok { + if rf, ok := ret.Get(1).(func(device.NewDeviceParams) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) @@ -36,15 +36,15 @@ func (_m *Repository) Create(_a0 model.NewDevice) (*model.Device, error) { } // Delete provides a mock function with given fields: _a0 -func (_m *Repository) Delete(_a0 string) (*model.Device, error) { +func (_m *Repository) Delete(_a0 string) (*device.Device, error) { ret := _m.Called(_a0) - var r0 *model.Device - if rf, ok := ret.Get(0).(func(string) *model.Device); ok { + var r0 *device.Device + if rf, ok := ret.Get(0).(func(string) *device.Device); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Device) + r0 = ret.Get(0).(*device.Device) } } @@ -59,20 +59,20 @@ func (_m *Repository) Delete(_a0 string) (*model.Device, error) { } // Get provides a mock function with given fields: _a0 -func (_m *Repository) Get(_a0 model.Device) ([]*model.Device, error) { +func (_m *Repository) Get(_a0 device.Device) ([]*device.Device, error) { ret := _m.Called(_a0) - var r0 []*model.Device - if rf, ok := ret.Get(0).(func(model.Device) []*model.Device); ok { + var r0 []*device.Device + if rf, ok := ret.Get(0).(func(device.Device) []*device.Device); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*model.Device) + r0 = ret.Get(0).([]*device.Device) } } var r1 error - if rf, ok := ret.Get(1).(func(model.Device) error); ok { + if rf, ok := ret.Get(1).(func(device.Device) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) @@ -82,15 +82,15 @@ func (_m *Repository) Get(_a0 model.Device) ([]*model.Device, error) { } // GetAll provides a mock function with given fields: -func (_m *Repository) GetAll() ([]*model.Device, error) { +func (_m *Repository) GetAll() ([]*device.Device, error) { ret := _m.Called() - var r0 []*model.Device - if rf, ok := ret.Get(0).(func() []*model.Device); ok { + var r0 []*device.Device + if rf, ok := ret.Get(0).(func() []*device.Device); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*model.Device) + r0 = ret.Get(0).([]*device.Device) } } @@ -105,11 +105,11 @@ func (_m *Repository) GetAll() ([]*model.Device, error) { } // Update provides a mock function with given fields: _a0 -func (_m *Repository) Update(_a0 model.UpdateDevice) error { +func (_m *Repository) Update(_a0 device.UpdateDeviceParams) error { ret := _m.Called(_a0) var r0 error - if rf, ok := ret.Get(0).(func(model.UpdateDevice) error); ok { + if rf, ok := ret.Get(0).(func(device.UpdateDeviceParams) error); ok { r0 = rf(_a0) } else { r0 = ret.Error(0) diff --git a/mocks/endpoint/Repository.go b/mocks/endpoint/Repository.go deleted file mode 100644 index cb0b8c8f..00000000 --- a/mocks/endpoint/Repository.go +++ /dev/null @@ -1,119 +0,0 @@ -// Code generated by mockery v2.9.4. DO NOT EDIT. - -package mocks - -import ( - model "github.com/rna-vt/devicecommander/graph/model" - mock "github.com/stretchr/testify/mock" -) - -// Repository is an autogenerated mock type for the Repository type -type Repository struct { - mock.Mock -} - -// Create provides a mock function with given fields: _a0 -func (_m *Repository) Create(_a0 model.NewEndpoint) (*model.Endpoint, error) { - ret := _m.Called(_a0) - - var r0 *model.Endpoint - if rf, ok := ret.Get(0).(func(model.NewEndpoint) *model.Endpoint); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(model.NewEndpoint) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: _a0 -func (_m *Repository) Delete(_a0 string) (*model.Endpoint, error) { - ret := _m.Called(_a0) - - var r0 *model.Endpoint - if rf, ok := ret.Get(0).(func(string) *model.Endpoint); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Get provides a mock function with given fields: _a0 -func (_m *Repository) Get(_a0 model.Endpoint) ([]*model.Endpoint, error) { - ret := _m.Called(_a0) - - var r0 []*model.Endpoint - if rf, ok := ret.Get(0).(func(model.Endpoint) []*model.Endpoint); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]*model.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(model.Endpoint) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAll provides a mock function with given fields: -func (_m *Repository) GetAll() ([]*model.Endpoint, error) { - ret := _m.Called() - - var r0 []*model.Endpoint - if rf, ok := ret.Get(0).(func() []*model.Endpoint); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]*model.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Update provides a mock function with given fields: _a0 -func (_m *Repository) Update(_a0 model.UpdateEndpoint) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(model.UpdateEndpoint) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} diff --git a/mocks/parameter/Repository.go b/mocks/parameter/Repository.go deleted file mode 100644 index 88e84da8..00000000 --- a/mocks/parameter/Repository.go +++ /dev/null @@ -1,119 +0,0 @@ -// Code generated by mockery v2.9.4. DO NOT EDIT. - -package mocks - -import ( - model "github.com/rna-vt/devicecommander/graph/model" - mock "github.com/stretchr/testify/mock" -) - -// Repository is an autogenerated mock type for the Repository type -type Repository struct { - mock.Mock -} - -// Create provides a mock function with given fields: _a0 -func (_m *Repository) Create(_a0 model.NewParameter) (*model.Parameter, error) { - ret := _m.Called(_a0) - - var r0 *model.Parameter - if rf, ok := ret.Get(0).(func(model.NewParameter) *model.Parameter); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Parameter) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(model.NewParameter) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: _a0 -func (_m *Repository) Delete(_a0 string) (*model.Parameter, error) { - ret := _m.Called(_a0) - - var r0 *model.Parameter - if rf, ok := ret.Get(0).(func(string) *model.Parameter); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*model.Parameter) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Get provides a mock function with given fields: _a0 -func (_m *Repository) Get(_a0 model.Parameter) ([]*model.Parameter, error) { - ret := _m.Called(_a0) - - var r0 []*model.Parameter - if rf, ok := ret.Get(0).(func(model.Parameter) []*model.Parameter); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]*model.Parameter) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(model.Parameter) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAll provides a mock function with given fields: -func (_m *Repository) GetAll() ([]*model.Parameter, error) { - ret := _m.Called() - - var r0 []*model.Parameter - if rf, ok := ret.Get(0).(func() []*model.Parameter); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]*model.Parameter) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Update provides a mock function with given fields: _a0 -func (_m *Repository) Update(_a0 model.UpdateParameter) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(model.UpdateParameter) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} diff --git a/mocks/rest/routes/Router.go b/mocks/rest/routes/Router.go new file mode 100644 index 00000000..b2931d14 --- /dev/null +++ b/mocks/rest/routes/Router.go @@ -0,0 +1,10 @@ +// Code generated by mockery v2.9.4. DO NOT EDIT. + +package mocks + +import mock "github.com/stretchr/testify/mock" + +// Router is an autogenerated mock type for the Router type +type Router struct { + mock.Mock +} diff --git a/src/app/app.go b/src/app/app.go index eb527706..1a204d82 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -6,7 +6,6 @@ import ( "github.com/rna-vt/devicecommander/src/cluster" "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/endpoint" "github.com/rna-vt/devicecommander/src/rest/routes" ) @@ -16,7 +15,7 @@ type Application struct { Echo *echo.Echo Hostname string DeviceRepository device.Repository - EndpointRepository endpoint.Repository + EndpointRepository endpoint.EndpointRepository } // SystemInfo returns a stringified version of this api. diff --git a/src/cluster/cluster.go b/src/cluster/cluster.go index 498d50e9..86bf6e0a 100644 --- a/src/cluster/cluster.go +++ b/src/cluster/cluster.go @@ -7,7 +7,6 @@ import ( log "github.com/sirupsen/logrus" "github.com/spf13/viper" - "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" ) @@ -19,7 +18,7 @@ type Cluster interface { RunHealthCheckLoop(int) StopHealth() StopDiscovery() - HandleDiscoveredDevice(model.NewDevice) (model.Device, error) + HandleDiscoveredDevice(device.NewDeviceParams) (device.Device, error) } // Cluster is responsible for maintaining the cluster like state of DeviceCommander. @@ -112,7 +111,7 @@ func (c DeviceCluster) RunHealthCheckLoop(healthCheckPeriod int) { c.logger.Info("Ticker stopped by healthStop chan") return default: - devices, err := c.DeviceRepository.Get(model.Device{ + devices, err := c.DeviceRepository.Get(device.Device{ Active: true, }) @@ -123,18 +122,18 @@ func (c DeviceCluster) RunHealthCheckLoop(healthCheckPeriod int) { return } - for _, d := range devices { - dev := device.NewDeviceWrapper(*d) + for _, dev := range devices { + // dev := device.NewDeviceWrapper(*d) - resp, err := c.DeviceClient.Health(dev) + resp, err := c.DeviceClient.Health(*dev) if err != nil { - c.logger.Warn(fmt.Sprintf("error checking health for device [%s] %s", d.ID.String(), err)) + c.logger.Warn(fmt.Sprintf("error checking health for device [%s] %s", dev.ID.String(), err)) } else { - result := c.DeviceClient.EvaluateHealthCheckResponse(resp, dev) + result := c.DeviceClient.EvaluateHealthCheckResponse(resp, *dev) if result { - c.logger.Trace(fmt.Sprintf("device [%s] is healthy", d.ID.String())) + c.logger.Trace(fmt.Sprintf("device [%s] is healthy", dev.ID.String())) } else { - c.logger.Trace(fmt.Sprintf("device [%s] is not healthy", d.ID.String())) + c.logger.Trace(fmt.Sprintf("device [%s] is not healthy", dev.ID.String())) } } } diff --git a/src/cluster/cluster_test.go b/src/cluster/cluster_test.go index fd28c83c..844be457 100644 --- a/src/cluster/cluster_test.go +++ b/src/cluster/cluster_test.go @@ -11,10 +11,8 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" - "github.com/rna-vt/devicecommander/graph/model" mockdevice "github.com/rna-vt/devicecommander/mocks/device" "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/test" "github.com/rna-vt/devicecommander/src/utilities" ) @@ -37,9 +35,9 @@ func (s *ClusterSuite) SetupSuite() { ) } -func GenerateDevices(count int) []*model.Device { - devices := test.GenerateRandomNewDevices(count) - collection := []*model.Device{} +func GenerateDevices(count int) []*device.Device { + devices := device.GenerateRandomNewDeviceParams(count) + collection := []*device.Device{} for _, d := range devices { tmpDev := device.FromNewDevice(d) collection = append(collection, &tmpDev) @@ -52,16 +50,16 @@ func (s *ClusterSuite) TestRunHealthCheckLoop() { fmt.Println(len(mockDevices)) - s.mockDeviceRepository.On("Get", mock.AnythingOfType("model.Device")).Return(mockDevices, nil) + s.mockDeviceRepository.On("Get", mock.AnythingOfType("device.Device")).Return(mockDevices, nil) tmpResponse := http.Response{ Status: "200", Body: io.NopCloser(strings.NewReader("healthy")), } - s.mockDeviceClient.On("Health", mock.AnythingOfType("device.BasicDevice")).Return(&tmpResponse, nil) + s.mockDeviceClient.On("Health", mock.AnythingOfType("device.Device")).Return(&tmpResponse, nil) - s.mockDeviceClient.On("EvaluateHealthCheckResponse", mock.AnythingOfType("*http.Response"), mock.AnythingOfType("device.BasicDevice")).Return(true) + s.mockDeviceClient.On("EvaluateHealthCheckResponse", mock.AnythingOfType("*http.Response"), mock.AnythingOfType("device.Device")).Return(true) go s.cluster.RunHealthCheckLoop(1) @@ -69,7 +67,7 @@ func (s *ClusterSuite) TestRunHealthCheckLoop() { s.cluster.StopHealth() - s.mockDeviceRepository.AssertCalled(s.T(), "Get", model.Device{Active: true}) + s.mockDeviceRepository.AssertCalled(s.T(), "Get", device.Device{Active: true}) s.mockDeviceRepository.AssertNumberOfCalls(s.T(), "Get", 2) } diff --git a/src/cluster/registration.go b/src/cluster/registration.go index 6ae8f829..35a730d8 100644 --- a/src/cluster/registration.go +++ b/src/cluster/registration.go @@ -6,7 +6,6 @@ import ( "strconv" "time" - "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/scanner" ) @@ -14,7 +13,7 @@ import ( // DeviceDiscovery will start an ArpScanner and use its results to create new // Devices in the database if they do not already exist. func (c DeviceCluster) DeviceDiscovery(scanDurationSeconds int) { - newDevices := make(chan model.NewDevice) + newDevices := make(chan device.NewDeviceParams) defer close(newDevices) stop := make(chan struct{}) // defer close(stop) @@ -39,7 +38,7 @@ func (c DeviceCluster) DeviceDiscovery(scanDurationSeconds int) { c.logger.Error(err) } - err = device.NewDeviceWrapper(d).RunHealthCheck(c.DeviceClient) + err = d.RunHealthCheck(c.DeviceClient) if err != nil { c.logger.Error(err) } @@ -51,30 +50,30 @@ func (c DeviceCluster) DeviceDiscovery(scanDurationSeconds int) { // HandleDiscoveredDevice does this with some additional steps. For example: // 1. does the Device already exist in the DB? (MAC address is the unique identifier in this case). // 2. immediately check its health. -func (c DeviceCluster) HandleDiscoveredDevice(newDevice model.NewDevice) (model.Device, error) { - results, err := c.DeviceRepository.Get(model.Device{ +func (c DeviceCluster) HandleDiscoveredDevice(newDevice device.NewDeviceParams) (device.Device, error) { + results, err := c.DeviceRepository.Get(device.Device{ MAC: *newDevice.Mac, }) if err != nil { - return model.Device{}, err + return device.Device{}, err } - discoveredDevice := new(model.Device) + discoveredDevice := new(device.Device) switch len(results) { case 0: discoveredDevice, err = c.DeviceRepository.Create(newDevice) if err != nil { - return model.Device{}, err + return device.Device{}, err } case 1: discoveredDevice := device.FromNewDevice(newDevice) discoveredDevice.Active = true if err := c.DeviceRepository.Update(updateDeviceFromDevice(&discoveredDevice)); err != nil { - return model.Device{}, err + return device.Device{}, err } default: - return model.Device{}, errors.New("multiple results returned for 1 mac address") + return device.Device{}, errors.New("multiple results returned for 1 mac address") } c.logger.Debugf("registered mac address [%s] with id [%s] at [%s]:[%s]", @@ -86,9 +85,9 @@ func (c DeviceCluster) HandleDiscoveredDevice(newDevice model.NewDevice) (model. return *discoveredDevice, nil } -// updateDeviceFromDevice builds a model.UpdateDevice from a model.Device. -func updateDeviceFromDevice(d *model.Device) model.UpdateDevice { - updateDevice := model.UpdateDevice{ +// updateDeviceFromDevice builds a device.UpdateDeviceParams from a device.Device. +func updateDeviceFromDevice(d *device.Device) device.UpdateDeviceParams { + updateDevice := device.UpdateDeviceParams{ Mac: &d.MAC, Host: &d.Host, Port: &d.Port, diff --git a/src/cluster/registration_test.go b/src/cluster/registration_test.go index afccbc44..9350089c 100644 --- a/src/cluster/registration_test.go +++ b/src/cluster/registration_test.go @@ -5,14 +5,14 @@ import ( "github.com/stretchr/testify/mock" - "github.com/rna-vt/devicecommander/graph/model" + "github.com/rna-vt/devicecommander/src/device" ) func (s *ClusterSuite) TestHandleDiscoveredDevice() { devices := GenerateDevices(2) - newDevices := make([]model.NewDevice, len(devices)) + newDevices := make([]device.NewDeviceParams, len(devices)) for i, d := range devices { - newDevices[i] = model.NewDevice{ + newDevices[i] = device.NewDeviceParams{ Mac: &d.MAC, Host: d.Host, Port: d.Port, @@ -20,10 +20,10 @@ func (s *ClusterSuite) TestHandleDiscoveredDevice() { } // New, Healthy Device - s.mockDeviceRepository.On("Get", mock.AnythingOfType("model.Device")).Return([]*model.Device{}, nil).Once() - s.mockDeviceRepository.On("Create", mock.AnythingOfType("model.NewDevice")).Return(devices[0], nil).Once() - s.mockDeviceClient.On("Health", mock.AnythingOfType("device.BasicDevice")).Return(nil, nil) - s.mockDeviceClient.On("EvaluateHealthCheckResponse", (*http.Response)(nil), mock.AnythingOfType("device.BasicDevice")).Return(true) + s.mockDeviceRepository.On("Get", mock.AnythingOfType("device.Device")).Return([]*device.Device{}, nil).Once() + s.mockDeviceRepository.On("Create", mock.AnythingOfType("device.NewDeviceParams")).Return(devices[0], nil).Once() + s.mockDeviceClient.On("Health", mock.AnythingOfType("device.Device")).Return(nil, nil) + s.mockDeviceClient.On("EvaluateHealthCheckResponse", (*http.Response)(nil), mock.AnythingOfType("device.Device")).Return(true) d, err := s.cluster.HandleDiscoveredDevice(newDevices[0]) s.Equal(err, nil) s.Equal(newDevices[0].Host, d.Host) diff --git a/src/device/client.go b/src/device/client.go index 08535c08..03ed6fd9 100644 --- a/src/device/client.go +++ b/src/device/client.go @@ -8,17 +8,15 @@ import ( "strconv" log "github.com/sirupsen/logrus" - - "github.com/rna-vt/devicecommander/graph/model" ) // DeviceClient implements the common http actions when interacting with a device. type Client interface { - Info(Device) (model.NewDevice, error) + Info(Device) (NewDeviceParams, error) Health(Device) (*http.Response, error) EvaluateHealthCheckResponse(resp *http.Response, d Device) bool Specification(Device) (*http.Response, error) - EvaluateSpecificationResponse(*http.Response) (model.Device, error) + EvaluateSpecificationResponse(*http.Response) (Device, error) } // HTTPDeviceClient is an implementation of the IDeviceClient. It communicates @@ -42,7 +40,7 @@ func (c HTTPDeviceClient) dangerousHTTPGet(url string) (resp *http.Response, err return http.Get(url) } -func (c HTTPDeviceClient) Info(d Device) (model.NewDevice, error) { +func (c HTTPDeviceClient) Info(d Device) (NewDeviceParams, error) { panic("function not implemented") } @@ -72,12 +70,12 @@ func (c HTTPDeviceClient) EvaluateHealthCheckResponse(resp *http.Response, d Dev switch resp.StatusCode { case http.StatusOK: - c.logger.WithFields(log.Fields{"event": "isHealthy"}).Info(d.ID()) + c.logger.WithFields(log.Fields{"event": "isHealthy"}).Info(d.ID) healthy = true case http.StatusNotFound: - c.logger.Error("Registered Device Not Found: " + d.ID().String()) + c.logger.Error("Registered Device Not Found: " + d.ID.String()) default: - c.logger.Error("Unexpected Result: " + d.ID().String()) + c.logger.Error("Unexpected Result: " + d.ID.String()) c.logger.Error("Status Code: " + strconv.Itoa(resp.StatusCode)) c.logger.Error("Response: " + string(body)) } @@ -95,8 +93,8 @@ func (c HTTPDeviceClient) Specification(d Device) (*http.Response, error) { return r, nil } -func (c HTTPDeviceClient) EvaluateSpecificationResponse(resp *http.Response) (model.Device, error) { - dev := model.Device{} +func (c HTTPDeviceClient) EvaluateSpecificationResponse(resp *http.Response) (Device, error) { + dev := Device{} defer resp.Body.Close() err := json.NewDecoder(resp.Body).Decode(&dev) diff --git a/src/device/device.go b/src/device/device.go index e06cbe3d..34d51167 100644 --- a/src/device/device.go +++ b/src/device/device.go @@ -8,13 +8,9 @@ import ( "github.com/google/uuid" log "github.com/sirupsen/logrus" "github.com/spf13/viper" - - "github.com/rna-vt/devicecommander/graph/model" ) -type Device interface { - NewDeviceFromRequestBody(body io.ReadCloser) (model.NewDevice, error) - ID() uuid.UUID +type BasicDevice interface { URL() string protocol() string ProcessHealthCheckResult(result bool) int @@ -22,14 +18,27 @@ type Device interface { RunHealthCheck(client Client) error } +// NewDeviceFromRequestBody creates a new instance of a NewDevice. +func NewDeviceFromRequestBody(body io.ReadCloser) (NewDeviceParams, error) { + defer body.Close() + decoder := json.NewDecoder(body) + var dev NewDeviceParams + + if err := decoder.Decode(&dev); err != nil { + return dev, err + } + + return dev, nil +} + // DeviceFromNewDevice generates a Device from a NewDevice with the correct instantiations. // This should be the primary method for creating model.Device(s). -func FromNewDevice(newDeviceArgs model.NewDevice) model.Device { - newDevice := model.Device{ +func FromNewDevice(newDeviceArgs NewDeviceParams) Device { + newDevice := Device{ ID: uuid.New(), Host: newDeviceArgs.Host, Port: newDeviceArgs.Port, - Endpoints: []model.Endpoint{}, + Endpoints: []Endpoint{}, } if newDeviceArgs.Mac != nil { @@ -41,24 +50,62 @@ func FromNewDevice(newDeviceArgs model.NewDevice) model.Device { // Device is a wrapper for the Device model. It aims to provide a helpful // layer of abstraction away from the gqlgen/postgres models. -type BasicDevice struct { - Device *model.Device +type Device struct { + + // the UUID for the device. + // + // required: true + // example: 705e4dcb-3ecd-24f3-3a35-3e926e4bded5 + ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` + + // the MAC address for this device. + // required: true + MAC string `json:"MAC" gorm:"unique" faker:"mac_address"` + + // the human readable name of the device. + // required: false + Name string `json:"Name"` + + // the description of the device. + // required: false + Description string `json:"Description"` + + // the host address of the device. + // required: true + Host string `json:"Host" faker:"ipv4"` + + // the active port of the device. + // required: true + Port int `json:"Port" faker:"boundary_start=49152, boundary_end=65535"` + + // the count of failed actions by the device. + // required: false + Failures int `json:"Failures" faker:"boundary_start=0, boundary_end=5"` + + // a flag representing the responsiveness of the device. + // required: false + Active bool `json:"Active"` + + // a list of endpoints available for quering on a device. + // required: false + Endpoints []Endpoint `json:"Endpoints" faker:"-"` + logger *log.Entry } -// NewDeviceWrapper creates a new instance of a device.Wrapper. -func NewDeviceWrapper(d model.Device) BasicDevice { - dev := BasicDevice{ - Device: &d, - logger: log.WithFields(log.Fields{"module": "device"}), - } +// // NewDeviceWrapper creates a new instance of a device.Wrapper. +// func NewDevice(d model.Device) Device { +// dev := Device{ +// Device: &d, +// logger: log.WithFields(log.Fields{"module": "device"}), +// } - return dev -} +// return dev +// } // NewDevice creates a barebones new instance of a Device with a host and port. -func NewDevice(host string, port int) (model.Device, error) { - dev := model.Device{ +func NewDevice(host string, port int) (Device, error) { + dev := Device{ Host: host, Port: port, Failures: 0, @@ -67,32 +114,15 @@ func NewDevice(host string, port int) (model.Device, error) { return dev, nil } -// NewDeviceFromRequestBody creates a new instance of a NewDevice. -func (d BasicDevice) NewDeviceFromRequestBody(body io.ReadCloser) (model.NewDevice, error) { - defer body.Close() - decoder := json.NewDecoder(body) - var dev model.NewDevice - - if err := decoder.Decode(&dev); err != nil { - return dev, err - } - - return dev, nil -} - -func (d BasicDevice) ID() uuid.UUID { - return d.Device.ID -} - // URL returns a network address including the ip address and port that this device is listening on. -func (d BasicDevice) URL() string { - return fmt.Sprintf("%s://%s:%d", d.protocol(), d.Device.Host, d.Device.Port) +func (d Device) URL() string { + return fmt.Sprintf("%s://%s:%d", d.protocol(), d.Host, d.Port) } // protocol determines the http/https protocol by Port allocation. -func (d BasicDevice) protocol() string { +func (d Device) protocol() string { var protocol string - if d.Device.Port == viper.GetInt("DEFAULT_TLS_PORT") { + if d.Port == viper.GetInt("DEFAULT_TLS_PORT") { protocol = "https" } else { protocol = "http" @@ -101,16 +131,16 @@ func (d BasicDevice) protocol() string { } // ProcessHealthCheckResult updates health check failure count & returns the failure count. -func (d BasicDevice) ProcessHealthCheckResult(result bool) int { +func (d Device) ProcessHealthCheckResult(result bool) int { if result { // Healthy return 0 } - return d.Device.Failures + 1 + return d.Failures + 1 } // Unresponsive determines the state of the device relative to its past performance. // If true, device should be deregistered. -func (d BasicDevice) Unresponsive() bool { +func (d Device) Unresponsive() bool { failThreshold := 3 - return d.Device.Failures >= failThreshold + return d.Failures >= failThreshold } diff --git a/src/device/device_test.go b/src/device/device_test.go index d46ec9a8..89f1df6b 100644 --- a/src/device/device_test.go +++ b/src/device/device_test.go @@ -15,8 +15,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" - "github.com/rna-vt/devicecommander/graph/model" - "github.com/rna-vt/devicecommander/src/test" "github.com/rna-vt/devicecommander/src/utilities" ) @@ -54,7 +52,7 @@ func (s *DeviceServiceSuite) SetupSuite() { } func (s *DeviceServiceSuite) TestDeviceFromNewDeviceWith() { - testNewDevice := test.GenerateRandomNewDevices(1)[0] + testNewDevice := GenerateRandomNewDeviceParams(1)[0] newDeviceResult := FromNewDevice(testNewDevice) @@ -63,25 +61,15 @@ func (s *DeviceServiceSuite) TestDeviceFromNewDeviceWith() { assert.NotNil(s.T(), newDeviceResult.Endpoints, "the Endpoints array is initialized") } -func (s *DeviceServiceSuite) TestNewDeviceWrapper() { - testNewDevice := test.GenerateRandomNewDevices(1)[0] - - newDeviceResult := FromNewDevice(testNewDevice) - - wrapper := NewDeviceWrapper(newDeviceResult) - - assert.Equal(s.T(), wrapper.Device.ID, newDeviceResult.ID, "the wrapper should have the same ID as the Device") -} - func (s *DeviceServiceSuite) TestNewDeviceFromRequestBody() { - testNewDevice := test.GenerateRandomNewDevices(1)[0] + testNewDevice := GenerateRandomNewDeviceParams(1)[0] b, err := json.Marshal(testNewDevice) assert.Nil(s.T(), err) r := ioutil.NopCloser(strings.NewReader(string(b))) // r type is io.ReadCloser - newDevice, err := BasicDevice{}.NewDeviceFromRequestBody(r) + newDevice, err := NewDeviceFromRequestBody(r) assert.Nil(s.T(), err) assert.Equal(s.T(), testNewDevice, newDevice, "the device should remain unchanged") @@ -109,11 +97,9 @@ func (s *DeviceServiceSuite) TestEvaluateSpecificationResponse() { client := HTTPDeviceClient{} - testDevice := BasicDevice{ - Device: &model.Device{ - Host: host, - Port: mockServerPort, - }, + testDevice := Device{ + Host: host, + Port: mockServerPort, } resp, err := client.Specification(testDevice) @@ -130,13 +116,11 @@ func (s *DeviceServiceSuite) TestEvaluateSpecificationResponse() { } func (s *DeviceServiceSuite) TestDeviceURL() { - testNewDevice := test.GenerateRandomNewDevices(1)[0] + testNewDeviceParams := GenerateRandomNewDeviceParams(1)[0] - newDeviceResult := FromNewDevice(testNewDevice) - - wrapper := NewDeviceWrapper(newDeviceResult) + testDevice := FromNewDevice(testNewDeviceParams) - devURL := wrapper.URL() + devURL := testDevice.URL() // validate the URL _, err := url.ParseRequestURI(devURL) assert.Nil(s.T(), err) @@ -146,6 +130,17 @@ func (s *DeviceServiceSuite) TestDeviceURL() { assert.NotEqual(s.T(), lastChar, "/", "the URL should not end in a \"/\"") } +func (s *DeviceServiceSuite) TestGenerateRandomNewDevice() { + testLength := 3 + testNewDevices := GenerateRandomNewDeviceParams(testLength) + + for _, v := range testNewDevices { + s.Require().NotNil(v, "all of the devices should not be nil") + } + + s.Equal(len(testNewDevices), testLength, "there should be the correct number of devices") +} + // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run. func TestDeviceServiceSuite(t *testing.T) { diff --git a/src/endpoint/endpoint.go b/src/device/endpoint.go similarity index 57% rename from src/endpoint/endpoint.go rename to src/device/endpoint.go index cc078cc6..1b2c3aeb 100644 --- a/src/endpoint/endpoint.go +++ b/src/device/endpoint.go @@ -1,38 +1,42 @@ -package endpoint +package device import ( "github.com/google/uuid" log "github.com/sirupsen/logrus" - - "github.com/rna-vt/devicecommander/graph/model" - "github.com/rna-vt/devicecommander/src/device" ) -type Endpoint interface { +type DeviceEndpoint interface { Execute(map[string]interface{}) error } // DeviceEndpoint implements the Endpoint interface. It provides a functional // layer for interacting with a specific Device's endpoint. -type DeviceEndpoint struct { - model.Endpoint - Device device.Device +type Endpoint struct { + // model.Endpoint + ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` + DeviceID uuid.UUID `json:"DeviceID" faker:"uuid_hyphenated"` + Method string `json:"Method"` + Type string `json:"Type" faker:"oneof: get, set"` + Description *string `json:"Description"` + Path *string `json:"Path"` + Parameters []Parameter `json:"Parameters,omitempty"` + Device Device } // FromNewEndpoint generates an Endpoint from a NewEndpoint with the correctly // instantiated fields. This should be the primary way in which an Endpoint is generated. -func FromNewEndpoint(input model.NewEndpoint) (model.Endpoint, error) { +func FromNewEndpoint(input NewEndpointParams) (Endpoint, error) { deviceUUID, err := uuid.Parse(input.DeviceID) if err != nil { log.Error(err) } - end := model.Endpoint{ + end := Endpoint{ ID: uuid.New(), DeviceID: deviceUUID, Type: input.Type, Method: input.Method, - Parameters: []model.Parameter{}, + Parameters: []Parameter{}, } if input.Description != nil { @@ -43,13 +47,13 @@ func FromNewEndpoint(input model.NewEndpoint) (model.Endpoint, error) { } // NewDeviceEndpoint generates a DeviceEndpoint. -func NewDeviceEndpoint() *DeviceEndpoint { - return &DeviceEndpoint{} +func NewDeviceEndpoint() *Endpoint { + return &Endpoint{} } // Execute carries out the action associated with the Device's endpoint // by communicating with the device. -func (e DeviceEndpoint) Execute(map[string]interface{}) error { +func (e Endpoint) Execute(map[string]interface{}) error { log.Println(e.Method) log.Println(e.Device.URL()) return nil diff --git a/src/device/endpoint_params.go b/src/device/endpoint_params.go new file mode 100644 index 00000000..6cbe970a --- /dev/null +++ b/src/device/endpoint_params.go @@ -0,0 +1,16 @@ +package device + +type NewEndpointParams struct { + DeviceID string `json:"DeviceID" faker:"uuid_hyphenated"` + Method string `json:"Method"` + Type string `json:"Type" faker:"oneof: get, set"` + Description *string `json:"Description"` +} + +type UpdateEndpointParams struct { + ID string `json:"ID" faker:"uuid_hyphenated"` + DeviceID *string `json:"DeviceID" faker:"uuid_hyphenated"` + Method *string `json:"Method"` + Type *string `json:"Type" faker:"oneof: get, set"` + Description *string `json:"Description"` +} diff --git a/src/device/endpoint_repository.go b/src/device/endpoint_repository.go new file mode 100644 index 00000000..6f41f82b --- /dev/null +++ b/src/device/endpoint_repository.go @@ -0,0 +1,11 @@ +package device + +// Repository prototypes the required interfaces for CRUD +// management of a collection of Endpoints. +type EndpointRepository interface { + Create(NewEndpointParams) (*Endpoint, error) + Update(UpdateEndpointParams) error + Delete(string) (*Endpoint, error) + Get(Endpoint) ([]*Endpoint, error) + GetAll() ([]*Endpoint, error) +} diff --git a/src/endpoint/endpoint_test.go b/src/device/endpoint_test.go similarity index 64% rename from src/endpoint/endpoint_test.go rename to src/device/endpoint_test.go index 099a5d1b..ae64953f 100644 --- a/src/endpoint/endpoint_test.go +++ b/src/device/endpoint_test.go @@ -1,4 +1,4 @@ -package endpoint +package device import ( "testing" @@ -7,8 +7,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" - "github.com/rna-vt/devicecommander/graph/model" - "github.com/rna-vt/devicecommander/src/test" "github.com/rna-vt/devicecommander/src/utilities" ) @@ -20,8 +18,8 @@ func (s *EndpointSuite) SetupSuite() { utilities.ConfigureEnvironment() } -func (s *EndpointSuite) CreateTestNewEndpoint() model.NewEndpoint { - return test.GenerateRandomNewEndpoints(uuid.New().String(), 1)[0] +func (s *EndpointSuite) CreateTestNewEndpoint() NewEndpointParams { + return GenerateRandomNewEndpointParams(uuid.New().String(), 1)[0] } func (s *EndpointSuite) TestNewEndpoint() { @@ -36,6 +34,18 @@ func (s *EndpointSuite) TestNewEndpoint() { assert.Equal(s.T(), testNewEndpoint.Description, testEndpoint.Description, "the description should carry through to the NewEndpoint") } +func (s *EndpointSuite) TestGenerateRandomNewEndpoints() { + testLength := 3 + tmpDeviceID := uuid.New().String() + testNewEndpoints := GenerateRandomNewEndpointParams(tmpDeviceID, testLength) + + s.Equal(len(testNewEndpoints), testLength, "there should be the correct number of endpoints") + + testNewEndpoint := testNewEndpoints[0] + + s.Equal(testNewEndpoint.DeviceID, tmpDeviceID, "the NewEndpoint should have the correct DeviceID") +} + // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run. func TestEndpointSuite(t *testing.T) { diff --git a/src/device/health.go b/src/device/health.go index fb5fcca0..644f878e 100644 --- a/src/device/health.go +++ b/src/device/health.go @@ -6,21 +6,21 @@ import ( // CheckHealth probes the health endpoint of the device in question. The health // endpoint is currently at Device.URL()/health. -func (d BasicDevice) RunHealthCheck(client Client) error { +func (d Device) RunHealthCheck(client Client) error { resp, err := client.Health(d) if err != nil { - d.logger.Warn(fmt.Sprintf("Error checking [%s] %s", d.Device.ID.String(), err)) + d.logger.Warn(fmt.Sprintf("Error checking [%s] %s", d.ID.String(), err)) } result := client.EvaluateHealthCheckResponse(resp, d) if result { - d.logger.Trace(fmt.Sprintf("device [%s] is healthy", d.Device.ID.String())) + d.logger.Trace(fmt.Sprintf("device [%s] is healthy", d.ID.String())) } else { - d.logger.Trace(fmt.Sprintf("device [%s] is not healthy", d.Device.ID.String())) + d.logger.Trace(fmt.Sprintf("device [%s] is not healthy", d.ID.String())) } - d.Device.Failures = d.ProcessHealthCheckResult(result) + d.Failures = d.ProcessHealthCheckResult(result) // TODO: need to cleanup unresponsive nodes somewhere // if d.Unresponsive() { diff --git a/src/parameter/parameter.go b/src/device/parameter.go similarity index 55% rename from src/parameter/parameter.go rename to src/device/parameter.go index dae1c923..21e1f475 100644 --- a/src/parameter/parameter.go +++ b/src/device/parameter.go @@ -1,23 +1,25 @@ -package parameter +package device import ( "github.com/google/uuid" - - "github.com/rna-vt/devicecommander/graph/model" ) type Parameter struct { - model.Parameter + ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` + EndpointID uuid.UUID `json:"EndpointID" faker:"uuid_hyphenated"` + Name string `json:"Name"` + Description *string `json:"Description"` + Type string `json:"Type" faker:"oneof: string, int, bool"` } // FromNewParameter generates a Parameter{} from a NewParameter with the correctly // instantiated fields. This should be the primary way in which a Parameter is generated. -func FromNewParameter(input model.NewParameter) (model.Parameter, error) { +func FromNewParameter(input NewParameterParams) (Parameter, error) { endpointID, err := uuid.Parse(input.EndpointID) if err != nil { - return model.Parameter{}, err + return Parameter{}, err } - param := model.Parameter{ + param := Parameter{ ID: uuid.New(), EndpointID: endpointID, Name: input.Name, diff --git a/src/device/parameter_params.go b/src/device/parameter_params.go new file mode 100644 index 00000000..063f747a --- /dev/null +++ b/src/device/parameter_params.go @@ -0,0 +1,16 @@ +package device + +type NewParameterParams struct { + EndpointID string `json:"EndpointID" faker:"uuid_hyphenated"` + Name string `json:"Name"` + Description *string `json:"Description"` + Type string `json:"Type" faker:"oneof: string, int, bool"` +} + +type UpdateParameterParams struct { + ID string `json:"ID" faker:"uuid_hyphenated"` + EndpointID *string `json:"EndpointID" faker:"uuid_hyphenated"` + Name *string `json:"Name"` + Description *string `json:"Description"` + Type *string `json:"Type" faker:"oneof: string, int, bool"` +} diff --git a/src/device/parameter_repository.go b/src/device/parameter_repository.go new file mode 100644 index 00000000..6605fcd2 --- /dev/null +++ b/src/device/parameter_repository.go @@ -0,0 +1,11 @@ +package device + +// Repository prototypes the required interfaces for +// CRUD actions on a collection of Parameters. +type ParameterRepository interface { + Create(NewParameterParams) (*Parameter, error) + Update(UpdateParameterParams) error + Delete(string) (*Parameter, error) + Get(Parameter) ([]*Parameter, error) + GetAll() ([]*Parameter, error) +} diff --git a/src/parameter/parameter_test.go b/src/device/parameter_test.go similarity index 54% rename from src/parameter/parameter_test.go rename to src/device/parameter_test.go index 5adf7f7e..c69cb2d8 100644 --- a/src/parameter/parameter_test.go +++ b/src/device/parameter_test.go @@ -1,4 +1,4 @@ -package parameter +package device import ( "testing" @@ -7,7 +7,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" - "github.com/rna-vt/devicecommander/src/test" "github.com/rna-vt/devicecommander/src/utilities" ) @@ -21,7 +20,7 @@ func (s *ParameterSuite) SetupSuite() { func (s *ParameterSuite) TestNewParameter() { tmpUUID := uuid.New() - testNewParameter := test.GenerateRandomNewParameterForEndpoint(tmpUUID.String(), 1)[0] + testNewParameter := GenerateRandomNewParameterForEndpoint(tmpUUID.String(), 1)[0] newParameter, err := FromNewParameter(testNewParameter) assert.Nil(s.T(), err, "creating a new parameter from a NewParameter should not throw an error") @@ -33,13 +32,36 @@ func (s *ParameterSuite) TestNewParameter() { func (s *ParameterSuite) TestNewParameterInvalid() { tmpUUID := uuid.New() - testNewParameter := test.GenerateRandomNewParameterForEndpoint(tmpUUID.String(), 1)[0] + testNewParameter := GenerateRandomNewParameterForEndpoint(tmpUUID.String(), 1)[0] testNewParameter.EndpointID = "" _, err := FromNewParameter(testNewParameter) assert.NotNil(s.T(), err, "creating a new Parameter with a NewParameter with an invalid EndpointID should throw an error") } +func (s *ParameterSuite) GenerateRandomNewParameter() { + testLength := 3 + testNewParameters := GenerateRandomNewParameter(testLength) + + s.Equal(len(testNewParameters), testLength, "there should be the correct number of parameters") + + testNewParameter := testNewParameters[0] + + s.Nil(testNewParameter.EndpointID, "the NewParameter's EndpointID should not be initialized") +} + +func (s *ParameterSuite) GenerateRandomNewParameterForEndpoint() { + testLength := 3 + tmpEndpointID := uuid.New().String() + testNewParameters := GenerateRandomNewParameterForEndpoint(tmpEndpointID, testLength) + + s.Equal(len(testNewParameters), testLength, "there should be the correct number of parameters") + + testNewParameter := testNewParameters[0] + + s.Equal(testNewParameter.EndpointID, tmpEndpointID, "the NewParameter should have the correct EndpointID") +} + // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run. func TestParameterSuite(t *testing.T) { diff --git a/src/device/params.go b/src/device/params.go new file mode 100644 index 00000000..fab6654b --- /dev/null +++ b/src/device/params.go @@ -0,0 +1,21 @@ +package device + +// Device models. +type NewDeviceParams struct { + Mac *string `json:"MAC" faker:"mac_address"` + Name *string `json:"Name"` + Description *string `json:"Description"` + Host string `json:"Host" faker:"ipv4"` + Port int `json:"Port" faker:"boundary_start=49152, boundary_end=65535"` + Active *bool `json:"Active"` +} + +type UpdateDeviceParams struct { + ID string `json:"ID" faker:"uuid_hyphenated"` + Mac *string `json:"MAC" faker:"mac_address"` + Name *string `json:"Name"` + Description *string `json:"Description"` + Host *string `json:"Host" faker:"ipv4"` + Port *int `json:"Port" faker:"boundary_start=49152, boundary_end=65535"` + Active *bool `json:"Active"` +} diff --git a/src/device/repository.go b/src/device/repository.go index 284e5e7a..07e04129 100644 --- a/src/device/repository.go +++ b/src/device/repository.go @@ -1,13 +1,11 @@ package device -import "github.com/rna-vt/devicecommander/graph/model" - // DeviceCRUDRepository prototypes the required interfaces necessary to // interact with a collection of Devices in a Postgres DB. type Repository interface { - Create(model.NewDevice) (*model.Device, error) - Update(model.UpdateDevice) error - Delete(string) (*model.Device, error) - Get(model.Device) ([]*model.Device, error) - GetAll() ([]*model.Device, error) + Create(NewDeviceParams) (*Device, error) + Update(UpdateDeviceParams) error + Delete(string) (*Device, error) + Get(Device) ([]*Device, error) + GetAll() ([]*Device, error) } diff --git a/src/test/utils.go b/src/device/utils.go similarity index 55% rename from src/test/utils.go rename to src/device/utils.go index bcb81890..5e0c2770 100644 --- a/src/test/utils.go +++ b/src/device/utils.go @@ -1,23 +1,15 @@ -package test +package device import ( - "math/rand" - "time" + "log" "github.com/bxcodec/faker/v3" - log "github.com/sirupsen/logrus" - - "github.com/rna-vt/devicecommander/graph/model" ) -func init() { - rand.Seed(time.Now().UnixNano()) -} - -func GenerateRandomNewDevices(count int) []model.NewDevice { - collection := make([]model.NewDevice, count) +func GenerateRandomNewDeviceParams(count int) []NewDeviceParams { + collection := make([]NewDeviceParams, count) for index := range collection { - tmpItem := model.NewDevice{} + tmpItem := NewDeviceParams{} err := faker.FakeData(&tmpItem) if err != nil { log.Fatal(err) @@ -27,10 +19,10 @@ func GenerateRandomNewDevices(count int) []model.NewDevice { return collection } -func GenerateRandomNewEndpoints(deviceID string, count int) []model.NewEndpoint { - collection := []model.NewEndpoint{} +func GenerateRandomNewEndpointParams(deviceID string, count int) []NewEndpointParams { + collection := []NewEndpointParams{} for i := 0; i < count; i++ { - tmpEndpoint := model.NewEndpoint{} + tmpEndpoint := NewEndpointParams{} err := faker.FakeData(&tmpEndpoint) if err != nil { log.Fatal(err) @@ -42,10 +34,10 @@ func GenerateRandomNewEndpoints(deviceID string, count int) []model.NewEndpoint return collection } -func GenerateRandomNewParameter(count int) []model.NewParameter { - collection := []model.NewParameter{} +func GenerateRandomNewParameter(count int) []NewParameterParams { + collection := []NewParameterParams{} for i := 0; i < count; i++ { - tmpParam := model.NewParameter{} + tmpParam := NewParameterParams{} err := faker.FakeData(&tmpParam) if err != nil { log.Fatal(err) @@ -56,10 +48,10 @@ func GenerateRandomNewParameter(count int) []model.NewParameter { return collection } -func GenerateRandomNewParameterForEndpoint(endpointID string, count int) []model.NewParameter { - collection := []model.NewParameter{} +func GenerateRandomNewParameterForEndpoint(endpointID string, count int) []NewParameterParams { + collection := []NewParameterParams{} for i := 0; i < count; i++ { - tmpParam := model.NewParameter{} + tmpParam := NewParameterParams{} err := faker.FakeData(&tmpParam) if err != nil { log.Fatal(err) diff --git a/src/docs/device_swagger.go b/src/docs/device_swagger.go index 4c1d489a..25236bdd 100644 --- a/src/docs/device_swagger.go +++ b/src/docs/device_swagger.go @@ -1,7 +1,7 @@ package docs import ( - "github.com/rna-vt/devicecommander/graph/model" + "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/rpc/method" ) @@ -14,7 +14,7 @@ import ( // swagger:response deviceResponse type deviceResponseWrapper struct { // in:body - Body model.Device + Body device.Device } // swagger:parameters idOfDevice diff --git a/src/endpoint/repository.go b/src/endpoint/repository.go deleted file mode 100644 index 1ed09066..00000000 --- a/src/endpoint/repository.go +++ /dev/null @@ -1,13 +0,0 @@ -package endpoint - -import "github.com/rna-vt/devicecommander/graph/model" - -// Repository prototypes the required interfaces for CRUD -// management of a collection of Endpoints. -type Repository interface { - Create(model.NewEndpoint) (*model.Endpoint, error) - Update(model.UpdateEndpoint) error - Delete(string) (*model.Endpoint, error) - Get(model.Endpoint) ([]*model.Endpoint, error) - GetAll() ([]*model.Endpoint, error) -} diff --git a/src/parameter/repository.go b/src/parameter/repository.go deleted file mode 100644 index d98745cf..00000000 --- a/src/parameter/repository.go +++ /dev/null @@ -1,13 +0,0 @@ -package parameter - -import "github.com/rna-vt/devicecommander/graph/model" - -// Repository prototypes the required interfaces for -// CRUD actions on a collection of Parameters. -type Repository interface { - Create(model.NewParameter) (*model.Parameter, error) - Update(model.UpdateParameter) error - Delete(string) (*model.Parameter, error) - Get(model.Parameter) ([]*model.Parameter, error) - GetAll() ([]*model.Parameter, error) -} diff --git a/src/postgres/config.go b/src/postgres/config.go index e8f02f09..cd035d2a 100644 --- a/src/postgres/config.go +++ b/src/postgres/config.go @@ -3,11 +3,10 @@ package postgres import ( "fmt" + "github.com/rna-vt/devicecommander/src/device" "github.com/spf13/viper" "gorm.io/driver/postgres" "gorm.io/gorm" - - "github.com/rna-vt/devicecommander/graph/model" ) // DBConfig encapsulates the information required for connecting to a database. @@ -51,7 +50,7 @@ func GetDBConnection(config DBConfig) (*gorm.DB, error) { // RunMigration makes sure each of the important models are fully migrated. func RunMigration(db *gorm.DB) error { - if err := db.AutoMigrate(&model.Device{}, &model.Endpoint{}, &model.Parameter{}); err != nil { + if err := db.AutoMigrate(&device.Device{}, &device.Endpoint{}, &device.Parameter{}); err != nil { return err } diff --git a/src/postgres/device/device_repository.go b/src/postgres/device/device_repository.go index 5ffb0916..1614d06f 100644 --- a/src/postgres/device/device_repository.go +++ b/src/postgres/device/device_repository.go @@ -6,7 +6,6 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" - "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -47,7 +46,7 @@ func (r Repository) Initialize() (Repository, error) { // Create on the DeviceRepository creates a new row in the Device table. // Due to the nested nature of Parameters. -func (r Repository) Create(newDeviceArgs model.NewDevice) (*model.Device, error) { +func (r Repository) Create(newDeviceArgs device.NewDeviceParams) (*device.Device, error) { newDevice := device.FromNewDevice(newDeviceArgs) result := r.DBConnection.Create(&newDevice) if result.Error != nil { @@ -60,12 +59,12 @@ func (r Repository) Create(newDeviceArgs model.NewDevice) (*model.Device, error) // Update on the DeviceRepository updates a single Device based off the ID of the UpdateDevice argument. // It will return an error if no device is updated. -func (r Repository) Update(input model.UpdateDevice) error { +func (r Repository) Update(input device.UpdateDeviceParams) error { id, err := uuid.Parse(input.ID) if err != nil { return err } - device := model.Device{ID: id} + device := device.Device{ID: id} result := r.DBConnection.Model(device).Updates(input) if result.Error != nil { return result.Error @@ -79,13 +78,13 @@ func (r Repository) Update(input model.UpdateDevice) error { return nil } -func (r Repository) Delete(id string) (*model.Device, error) { +func (r Repository) Delete(id string) (*device.Device, error) { uid, err := uuid.Parse(id) if err != nil { - return &model.Device{}, err + return &device.Device{}, err } - toBeDeleted := model.Device{ + toBeDeleted := device.Device{ ID: uid, } @@ -99,24 +98,24 @@ func (r Repository) Delete(id string) (*model.Device, error) { } for _, e := range results[0].Endpoints { - r.DBConnection.Delete(model.Parameter{}, model.Parameter{ + r.DBConnection.Delete(device.Parameter{}, device.Parameter{ EndpointID: e.ID, }) } - r.DBConnection.Delete(model.Endpoint{}, model.Endpoint{ + r.DBConnection.Delete(device.Endpoint{}, device.Endpoint{ DeviceID: uid, }) // TODO: Implement soft deletes - r.DBConnection.Select("Endpoints").Delete(model.Device{}, toBeDeleted) + r.DBConnection.Select("Endpoints").Delete(device.Device{}, toBeDeleted) r.logger.Trace("Deleted device " + id) return &toBeDeleted, nil } -func (r Repository) Get(devQuery model.Device) ([]*model.Device, error) { - devices := []*model.Device{} +func (r Repository) Get(devQuery device.Device) ([]*device.Device, error) { + devices := []*device.Device{} result := r.DBConnection.Preload(clause.Associations).Where(devQuery).Find(&devices) if result.Error != nil { return devices, result.Error @@ -125,8 +124,8 @@ func (r Repository) Get(devQuery model.Device) ([]*model.Device, error) { return devices, nil } -func (r Repository) GetAll() ([]*model.Device, error) { - devices := []*model.Device{} +func (r Repository) GetAll() ([]*device.Device, error) { + devices := []*device.Device{} result := r.DBConnection.Preload(clause.Associations).Find(&devices) if result.Error != nil { return devices, result.Error diff --git a/src/postgres/device/device_repository_test.go b/src/postgres/device/device_repository_test.go index 961a1edd..d9f91489 100644 --- a/src/postgres/device/device_repository_test.go +++ b/src/postgres/device/device_repository_test.go @@ -9,16 +9,14 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" - "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" - "github.com/rna-vt/devicecommander/src/test" "github.com/rna-vt/devicecommander/src/utilities" ) type PostgresDeviceRepositorySuite struct { suite.Suite - testDevices []model.Device + testDevices []device.Device repository device.Repository } @@ -31,15 +29,15 @@ func (s *PostgresDeviceRepositorySuite) SetupSuite() { s.repository = deviceRepository - dev, err := s.repository.Create(test.GenerateRandomNewDevices(1)[0]) + dev, err := s.repository.Create(device.GenerateRandomNewDeviceParams(1)[0]) assert.Nil(s.T(), err) // add device to test list for deletion after s.testDevices = append(s.testDevices, *dev) } -func (s *PostgresDeviceRepositorySuite) CreateTestDevice() model.Device { - testDevices := test.GenerateRandomNewDevices(1) +func (s *PostgresDeviceRepositorySuite) CreateTestDevice() device.Device { + testDevices := device.GenerateRandomNewDeviceParams(1) testDevice := testDevices[0] newDevice, err := s.repository.Create(testDevice) @@ -50,18 +48,10 @@ func (s *PostgresDeviceRepositorySuite) CreateTestDevice() model.Device { return *newDevice } -func (s *PostgresDeviceRepositorySuite) TestDeviceRepositoryImplementsCRUDInterface() { - // val := MyType("hello") - // testDevice := s.CreateTestDevice() - // _, ok := interface{}(testDevice).(DeviceCRUDRepository) - - // assert.Equal(s.T(), true, ok, "the device repository must implement the DeviceCRUDRepository interface") -} - func (s *PostgresDeviceRepositorySuite) TestGet() { testDevice := s.CreateTestDevice() - results, err := s.repository.Get(model.Device{ + results, err := s.repository.Get(device.Device{ ID: testDevice.ID, }) assert.Nil(s.T(), err) @@ -81,7 +71,7 @@ func (s *PostgresDeviceRepositorySuite) TestDelete() { assert.Equal(s.T(), deleteResult.ID, testDevice.ID, "the return from a delete should contain the deleted object") - getResults, err := s.repository.Get(model.Device{ + getResults, err := s.repository.Get(device.Device{ ID: testDevice.ID, }) assert.Nil(s.T(), err) @@ -93,13 +83,13 @@ func (s *PostgresDeviceRepositorySuite) TestUpdate() { testDevice := s.CreateTestDevice() tmpMAC := faker.MacAddress() - err := s.repository.Update(model.UpdateDevice{ + err := s.repository.Update(device.UpdateDeviceParams{ ID: testDevice.ID.String(), Mac: &tmpMAC, }) assert.Nil(s.T(), err) - getResults, err := s.repository.Get(model.Device{ + getResults, err := s.repository.Get(device.Device{ ID: testDevice.ID, }) assert.Nil(s.T(), err) @@ -110,7 +100,7 @@ func (s *PostgresDeviceRepositorySuite) TestUpdate() { func (s *PostgresDeviceRepositorySuite) TestUpdateNonExistent() { tmpMAC := faker.MacAddress() tmpUUID := uuid.New() - err := s.repository.Update(model.UpdateDevice{ + err := s.repository.Update(device.UpdateDeviceParams{ ID: tmpUUID.String(), Mac: &tmpMAC, }) @@ -126,7 +116,7 @@ func (s *PostgresDeviceRepositorySuite) AfterTest(_, _ string) { } } - s.testDevices = []model.Device{} + s.testDevices = []device.Device{} // require.NoError(s.T(), s.mock.ExpectationsWereMet()) } diff --git a/src/postgres/endpoint/endpoint_repository.go b/src/postgres/endpoint/endpoint_repository.go index ddb1e665..f2dee852 100644 --- a/src/postgres/endpoint/endpoint_repository.go +++ b/src/postgres/endpoint/endpoint_repository.go @@ -6,8 +6,7 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" - "github.com/rna-vt/devicecommander/graph/model" - "github.com/rna-vt/devicecommander/src/endpoint" + "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -47,8 +46,8 @@ func (r Repository) Initialize() (Repository, error) { return r, nil } -func (r Repository) Create(newDeviceArgs model.NewEndpoint) (*model.Endpoint, error) { - newEndpoint, err := endpoint.FromNewEndpoint(newDeviceArgs) +func (r Repository) Create(newDeviceArgs device.NewEndpointParams) (*device.Endpoint, error) { + newEndpoint, err := device.FromNewEndpoint(newDeviceArgs) if err != nil { return &newEndpoint, err } @@ -62,13 +61,13 @@ func (r Repository) Create(newDeviceArgs model.NewEndpoint) (*model.Endpoint, er return &newEndpoint, nil } -func (r Repository) Update(input model.UpdateEndpoint) error { +func (r Repository) Update(input device.UpdateEndpointParams) error { id, err := uuid.Parse(input.ID) if err != nil { return err } - end := model.Endpoint{ID: id} + end := device.Endpoint{ID: id} result := r.DBConnection.Model(end).Updates(input) if result.Error != nil { @@ -85,19 +84,19 @@ func (r Repository) Update(input model.UpdateEndpoint) error { // Delete on the EndpointRepository removes a single row from the Endpoint table by the // specific ID AND all of the Parameters associated with the EndpointID. -func (r Repository) Delete(id string) (*model.Endpoint, error) { - var toBeDeleted model.Endpoint +func (r Repository) Delete(id string) (*device.Endpoint, error) { + var toBeDeleted device.Endpoint endUUID, err := uuid.Parse(id) if err != nil { return &toBeDeleted, err } toBeDeleted.ID = endUUID - r.DBConnection.Delete(model.Parameter{}, model.Parameter{ + r.DBConnection.Delete(device.Parameter{}, device.Parameter{ EndpointID: endUUID, }) - r.DBConnection.Delete(model.Endpoint{}, toBeDeleted) + r.DBConnection.Delete(device.Endpoint{}, toBeDeleted) r.logger.Debug("Deleted endpoint " + id) return &toBeDeleted, nil @@ -105,8 +104,8 @@ func (r Repository) Delete(id string) (*model.Endpoint, error) { // Get on the EndpointRepository will retrieve all of the rows that match the query. The // associated objects (parameters) will be preloaded for convenience. -func (r Repository) Get(query model.Endpoint) ([]*model.Endpoint, error) { - endpoints := []*model.Endpoint{} +func (r Repository) Get(query device.Endpoint) ([]*device.Endpoint, error) { + endpoints := []*device.Endpoint{} result := r.DBConnection.Preload(clause.Associations).Where(query).Find(&endpoints) if result.Error != nil { return endpoints, result.Error @@ -115,8 +114,8 @@ func (r Repository) Get(query model.Endpoint) ([]*model.Endpoint, error) { return endpoints, nil } -func (r Repository) GetAll() ([]*model.Endpoint, error) { - endpoints := []*model.Endpoint{} +func (r Repository) GetAll() ([]*device.Endpoint, error) { + endpoints := []*device.Endpoint{} result := r.DBConnection.Preload(clause.Associations).Find(&endpoints) if result.Error != nil { return endpoints, result.Error diff --git a/src/postgres/endpoint/endpoint_repository_test.go b/src/postgres/endpoint/endpoint_repository_test.go index ec4a7550..618432ad 100644 --- a/src/postgres/endpoint/endpoint_repository_test.go +++ b/src/postgres/endpoint/endpoint_repository_test.go @@ -8,20 +8,17 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" - "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/endpoint" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" - "github.com/rna-vt/devicecommander/src/test" "github.com/rna-vt/devicecommander/src/utilities" ) type PostgresEndpointRepositorySuite struct { suite.Suite - testDevices []model.Device - testEndpoints []model.Endpoint - endpointRepository endpoint.Repository + testDevices []device.Device + testEndpoints []device.Endpoint + endpointRepository device.EndpointRepository deviceRepository device.Repository } @@ -38,19 +35,21 @@ func (s *PostgresEndpointRepositorySuite) SetupSuite() { s.endpointRepository = endpointRepository s.deviceRepository = deviceRepository - newDevices := test.GenerateRandomNewDevices(1) + newDevices := device.GenerateRandomNewDeviceParams(1) dev, err := s.deviceRepository.Create(newDevices[0]) s.Require().Nil(err, "creating a test device should not throw an error") s.testDevices = append(s.testDevices, *dev) } -func (s *PostgresEndpointRepositorySuite) CreateTestEndpoint() model.Endpoint { - testEndpoints := test.GenerateRandomNewEndpoints(s.testDevices[0].ID.String(), 1) +func (s *PostgresEndpointRepositorySuite) CreateTestEndpoint() device.Endpoint { + testEndpoints := device.GenerateRandomNewEndpointParams(s.testDevices[0].ID.String(), 1) testEndpoint := testEndpoints[0] end, err := s.endpointRepository.Create(testEndpoint) assert.Nil(s.T(), err) + s.testDevices[0].Endpoints = nil + end.Device = s.testDevices[0] s.testEndpoints = append(s.testEndpoints, *end) @@ -60,14 +59,13 @@ func (s *PostgresEndpointRepositorySuite) CreateTestEndpoint() model.Endpoint { func (s *PostgresEndpointRepositorySuite) TestGet() { testEndpoint := s.CreateTestEndpoint() - results, err := s.endpointRepository.Get(model.Endpoint{ + results, err := s.endpointRepository.Get(device.Endpoint{ ID: testEndpoint.ID, }) assert.Nil(s.T(), err) - assert.Equal(s.T(), 1, len(results), "there should only be a single return when searching by id") - - assert.Equal(s.T(), testEndpoint, *results[0], "the return from create should be equal to the return from get") + s.Equal(1, len(results), "there should only be a single return when searching by id") + s.Equal(testEndpoint, *results[0], "the return from create should be equal to the return from get") for _, p := range results[0].Parameters { assert.Equal(s.T(), testEndpoint.ID, p.EndpointID, "the new param should have the correct endpoint id") @@ -84,7 +82,7 @@ func (s *PostgresEndpointRepositorySuite) TestDelete() { assert.Equal(s.T(), deleteResult.ID, testEndpoint.ID, "the return from a delete should contain the deleted object") - getResults, err := s.endpointRepository.Get(model.Endpoint{ + getResults, err := s.endpointRepository.Get(device.Endpoint{ ID: testEndpoint.ID, }) assert.Nil(s.T(), err) @@ -98,13 +96,13 @@ func (s *PostgresEndpointRepositorySuite) TestUpdate() { testEndpoint := s.CreateTestEndpoint() tmpDesc := "update random test" - err := s.endpointRepository.Update(model.UpdateEndpoint{ + err := s.endpointRepository.Update(device.UpdateEndpointParams{ ID: testEndpoint.ID.String(), Description: &tmpDesc, }) assert.Nil(s.T(), err) - getResults, err := s.endpointRepository.Get(model.Endpoint{ + getResults, err := s.endpointRepository.Get(device.Endpoint{ ID: testEndpoint.ID, }) assert.Nil(s.T(), err) @@ -117,7 +115,7 @@ func (s *PostgresEndpointRepositorySuite) TestUpdate() { func (s *PostgresEndpointRepositorySuite) TestUpdateNonExistent() { tmpDesc := "non existent random test" tmpUUID := uuid.New() - err := s.endpointRepository.Update(model.UpdateEndpoint{ + err := s.endpointRepository.Update(device.UpdateEndpointParams{ ID: tmpUUID.String(), Description: &tmpDesc, }) @@ -136,7 +134,7 @@ func (s *PostgresEndpointRepositorySuite) TearDownSuite() { assert.Nil(s.T(), err) } - s.testDevices = []model.Device{} + s.testDevices = []device.Device{} } // In order for 'go test' to run this suite, we need to create diff --git a/src/postgres/parameter/parameter_repository.go b/src/postgres/parameter/parameter_repository.go index 92b62819..f94ae9eb 100644 --- a/src/postgres/parameter/parameter_repository.go +++ b/src/postgres/parameter/parameter_repository.go @@ -8,8 +8,7 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" - "github.com/rna-vt/devicecommander/graph/model" - "github.com/rna-vt/devicecommander/src/parameter" + "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -49,8 +48,8 @@ func (r Repository) Initialize() (Repository, error) { } // Create on the ParameterRepository creates a new row in the Parameter table in the postgres database. -func (r Repository) Create(newParameterArgs model.NewParameter) (*model.Parameter, error) { - newParameter, err := parameter.FromNewParameter(newParameterArgs) +func (r Repository) Create(newParameterArgs device.NewParameterParams) (*device.Parameter, error) { + newParameter, err := device.FromNewParameter(newParameterArgs) if err != nil { return &newParameter, err } @@ -65,13 +64,13 @@ func (r Repository) Create(newParameterArgs model.NewParameter) (*model.Paramete } // Update on the ParameterRepository updates a new single row in the Parameter table according to the specified UpdateParameter.ID. -func (r Repository) Update(input model.UpdateParameter) error { +func (r Repository) Update(input device.UpdateParameterParams) error { parameterID, err := uuid.Parse(input.ID) if err != nil { return err } - end := model.Parameter{ID: parameterID} + end := device.Parameter{ID: parameterID} result := r.DBConnection.Session(&gorm.Session{FullSaveAssociations: true}).Model(end).Updates(input) if result.Error != nil { @@ -83,8 +82,8 @@ func (r Repository) Update(input model.UpdateParameter) error { } // Delete on the ParameterRepository removes a single row from the Parameter table by the specific ID. -func (r Repository) Delete(id string) (*model.Parameter, error) { - var toBeDeleted model.Parameter +func (r Repository) Delete(id string) (*device.Parameter, error) { + var toBeDeleted device.Parameter parameterID, err := uuid.Parse(id) if err != nil { @@ -104,7 +103,7 @@ func (r Repository) Delete(id string) (*model.Parameter, error) { toBeDeleted = *results[0] // TODO: Implement soft deletes - r.DBConnection.Delete(model.Parameter{}, toBeDeleted) + r.DBConnection.Delete(device.Parameter{}, toBeDeleted) r.logger.Trace("Deleted Parameter " + id) return &toBeDeleted, nil @@ -112,8 +111,8 @@ func (r Repository) Delete(id string) (*model.Parameter, error) { // Get on the ParameterRepository will retrieve all of the rows that match the query. The // associated object (endpoint) will be preloaded for convenience. -func (r Repository) Get(query model.Parameter) ([]*model.Parameter, error) { - Parameters := []*model.Parameter{} +func (r Repository) Get(query device.Parameter) ([]*device.Parameter, error) { + Parameters := []*device.Parameter{} result := r.DBConnection.Preload(clause.Associations).Where(query).Find(&Parameters) if result.Error != nil { return Parameters, result.Error @@ -124,8 +123,8 @@ func (r Repository) Get(query model.Parameter) ([]*model.Parameter, error) { // GetAll on the ParameterRepository will retrieve all of the rows in the Parameter table. The // associated objects (endpoints) will be preloaded for convenience. -func (r Repository) GetAll() ([]*model.Parameter, error) { - Parameters := []*model.Parameter{} +func (r Repository) GetAll() ([]*device.Parameter, error) { + Parameters := []*device.Parameter{} result := r.DBConnection.Find(&Parameters) if result.Error != nil { return Parameters, result.Error diff --git a/src/postgres/parameter/parameter_repository_test.go b/src/postgres/parameter/parameter_repository_test.go index c721912f..1745cc8c 100644 --- a/src/postgres/parameter/parameter_repository_test.go +++ b/src/postgres/parameter/parameter_repository_test.go @@ -7,24 +7,22 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" - "github.com/rna-vt/devicecommander/graph/model" - "github.com/rna-vt/devicecommander/src/endpoint" - "github.com/rna-vt/devicecommander/src/parameter" + "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" + "github.com/rna-vt/devicecommander/src/postgres/endpoint" postgresEndpoint "github.com/rna-vt/devicecommander/src/postgres/endpoint" - "github.com/rna-vt/devicecommander/src/test" "github.com/rna-vt/devicecommander/src/utilities" ) type PostgresParameterRepositorySuite struct { suite.Suite - testDevices []model.Device - testEndpoints []model.Endpoint - testParameters []model.Parameter + testDevices []device.Device + testEndpoints []device.Endpoint + testParameters []device.Parameter deviceRepository postgresDevice.Repository endpointRepository endpoint.Repository - parameterRepository parameter.Repository + parameterRepository device.ParameterRepository } func (s *PostgresParameterRepositorySuite) SetupSuite() { @@ -44,11 +42,11 @@ func (s *PostgresParameterRepositorySuite) SetupSuite() { s.endpointRepository = endpointRepository s.parameterRepository = parameterRepository - newDevices := test.GenerateRandomNewDevices(1) + newDevices := device.GenerateRandomNewDeviceParams(1) dev, err := s.deviceRepository.Create(newDevices[0]) assert.Nil(s.T(), err) - testEndpoint := test.GenerateRandomNewEndpoints(dev.ID.String(), 1) + testEndpoint := device.GenerateRandomNewEndpointParams(dev.ID.String(), 1) end, err := s.endpointRepository.Create(testEndpoint[0]) assert.Nil(s.T(), err) @@ -57,9 +55,9 @@ func (s *PostgresParameterRepositorySuite) SetupSuite() { s.testEndpoints = append(s.testEndpoints, *end) } -func (s *PostgresParameterRepositorySuite) CreateTestParameter() model.Parameter { +func (s *PostgresParameterRepositorySuite) CreateTestParameter() device.Parameter { currentTestEndpoint := s.testEndpoints[0] - testParameters := test.GenerateRandomNewParameterForEndpoint(currentTestEndpoint.ID.String(), 1) + testParameters := device.GenerateRandomNewParameterForEndpoint(currentTestEndpoint.ID.String(), 1) param, err := s.parameterRepository.Create(testParameters[0]) assert.Nil(s.T(), err, "creating a test parameter should not throw an error") @@ -72,7 +70,7 @@ func (s *PostgresParameterRepositorySuite) CreateTestParameter() model.Parameter func (s *PostgresParameterRepositorySuite) TestGet() { testParameter := s.CreateTestParameter() - results, err := s.parameterRepository.Get(model.Parameter{ + results, err := s.parameterRepository.Get(device.Parameter{ ID: testParameter.ID, }) assert.Nil(s.T(), err) @@ -90,7 +88,7 @@ func (s *PostgresParameterRepositorySuite) TestDelete() { assert.Equal(s.T(), deleteResult.ID, testParameter.ID, "the return from a delete should contain the deleted object") - getResults, err := s.parameterRepository.Get(model.Parameter{ + getResults, err := s.parameterRepository.Get(device.Parameter{ ID: testParameter.ID, }) assert.Nil(s.T(), err) @@ -102,13 +100,13 @@ func (s *PostgresParameterRepositorySuite) TestUpdate() { testParameter := s.CreateTestParameter() tmpDesc := "Radom test update" - err := s.parameterRepository.Update(model.UpdateParameter{ + err := s.parameterRepository.Update(device.UpdateParameterParams{ ID: testParameter.ID.String(), Description: &tmpDesc, }) assert.Nil(s.T(), err) - getResults, err := s.parameterRepository.Get(model.Parameter{ + getResults, err := s.parameterRepository.Get(device.Parameter{ ID: testParameter.ID, }) assert.Nil(s.T(), err) diff --git a/src/rest/controllers/device.go b/src/rest/controllers/device.go index 65a1f9e4..7478d271 100644 --- a/src/rest/controllers/device.go +++ b/src/rest/controllers/device.go @@ -5,9 +5,8 @@ import ( "github.com/google/uuid" "github.com/labstack/echo" - "github.com/labstack/gommon/log" + log "github.com/sirupsen/logrus" - "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" @@ -31,7 +30,7 @@ func NewDeviceController() (DeviceController, error) { } func (controller DeviceController) Create(c echo.Context) error { - dev, err := device.BasicDevice{}.NewDeviceFromRequestBody(c.Request().Body) + dev, err := device.NewDeviceFromRequestBody(c.Request().Body) if err != nil { return err } @@ -59,7 +58,7 @@ func (controller DeviceController) GetDevice(c echo.Context) error { return err } - tmpDev := model.Device{ID: id} + tmpDev := device.Device{ID: id} device, err := controller.Repository.Get(tmpDev) if err != nil { return err @@ -67,3 +66,26 @@ func (controller DeviceController) GetDevice(c echo.Context) error { return c.JSON(http.StatusOK, &device) } + +func (controller DeviceController) Update(c echo.Context) error { + updateParams := new(device.UpdateDeviceParams) + if err := c.Bind(updateParams); err != nil { + return err + } + + err := controller.Repository.Update(*updateParams) + if err != nil { + return err + } + return c.JSON(http.StatusOK, true) +} + +func (controller DeviceController) Delete(c echo.Context) error { + log.Info("DEVICE_ID", c.Param("deviceID")) + toDelete, err := controller.Repository.Delete(c.Param("deviceID")) + if err != nil { + return err + } + + return c.JSON(http.StatusOK, &toDelete) +} diff --git a/src/rest/controllers/device_test.go b/src/rest/controllers/device_test.go new file mode 100644 index 00000000..060491cf --- /dev/null +++ b/src/rest/controllers/device_test.go @@ -0,0 +1,108 @@ +package controllers + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/google/uuid" + "github.com/labstack/echo" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + + mocks "github.com/rna-vt/devicecommander/mocks/device" + "github.com/rna-vt/devicecommander/src/device" +) + +type DeviceControllerSuite struct { + suite.Suite + controller DeviceController + mockDeviceRepository mocks.Repository + ctx context.Context +} + +func (s *DeviceControllerSuite) SetupSuite() { + s.mockDeviceRepository = mocks.Repository{} + s.controller = DeviceController{ + Repository: &s.mockDeviceRepository, + } + s.ctx = context.Background() +} + +func NewEchoContext(method, path string, data interface{}) echo.Context { + requestByte, _ := json.Marshal(data) + requestReader := bytes.NewReader(requestByte) + + req, err := http.NewRequest("POST", "/v1/device", requestReader) + if err != nil { + logrus.Error(err) + } + + e := echo.New() + res := httptest.NewRecorder() + return e.NewContext(req, res) +} + +func (s *DeviceControllerSuite) TestCreateDevice() { + newDevices := device.GenerateRandomNewDeviceParams(1) + + s.mockDeviceRepository.On("Create", newDevices[0]).Return(&device.Device{}, nil) + + err := s.controller.Create(NewEchoContext("POST", "/v1/device", newDevices[0])) + assert.Nil(s.T(), err) + + s.mockDeviceRepository.AssertCalled(s.T(), "Create", newDevices[0]) + + s.mockDeviceRepository.AssertExpectations(s.T()) +} + +func (s *DeviceControllerSuite) TestGetDevices() { + + s.mockDeviceRepository.On("GetAll").Return([]*device.Device{}, nil) + err := s.controller.GetAll(NewEchoContext("GET", "/v1/device", nil)) + assert.Nil(s.T(), err) + + s.mockDeviceRepository.AssertCalled(s.T(), "GetAll") + + s.mockDeviceRepository.AssertExpectations(s.T()) +} + +func (s *DeviceControllerSuite) TestDeleteDevice() { + randomUUID := uuid.New().String() + ctx := NewEchoContext("DELETE", "/v1/device/"+randomUUID, nil) + + s.mockDeviceRepository.On("Delete", randomUUID).Return(&device.Device{}, randomUUID) + err := s.controller.Delete(ctx) + assert.Nil(s.T(), err) + + s.mockDeviceRepository.AssertCalled(s.T(), "Delete", randomUUID) + + s.mockDeviceRepository.AssertExpectations(s.T()) +} + +func (s *DeviceControllerSuite) TestUpdateDevice() { + tmpName := "McTesterson" + updateInput := device.UpdateDeviceParams{ + ID: "uuid.string", + Name: &tmpName, + } + ctx := NewEchoContext("POST", "/v1/device", updateInput) + + s.mockDeviceRepository.On("Update", updateInput).Return(nil) + err := s.controller.Update(ctx) + assert.Nil(s.T(), err) + + s.mockDeviceRepository.AssertCalled(s.T(), "Update", updateInput) + + // s.mockDeviceRepository.AssertExpectations(s.T()) +} + +// In order for 'go test' to run this suite, we need to create +// a normal test function and pass our suite to suite.Run. +func TestDeviceControllerTestSuite(t *testing.T) { + suite.Run(t, new(DeviceControllerSuite)) +} diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index 673d8a7b..4f8d0648 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -14,5 +14,6 @@ func (r DeviceRouter) RegisterRoutes(e *echo.Echo) { api := e.Group("/v1/device") api.POST("/", r.DeviceController.Create) api.GET("/", r.DeviceController.GetAll) - api.GET("/device/:id", r.DeviceController.GetDevice) + api.GET("/:id", r.DeviceController.GetDevice) + api.DELETE("/:deviceID", r.DeviceController.GetDevice) } diff --git a/src/routes/graphql.go b/src/routes/graphql.go deleted file mode 100644 index aa8f4197..00000000 --- a/src/routes/graphql.go +++ /dev/null @@ -1,37 +0,0 @@ -package routes - -import ( - "github.com/99designs/gqlgen/graphql/handler" - "github.com/99designs/gqlgen/graphql/playground" - "github.com/labstack/echo" - - "github.com/rna-vt/devicecommander/graph" - "github.com/rna-vt/devicecommander/graph/generated" - "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/endpoint" -) - -func (a *APIService) addGraphQLRoutes(e *echo.Echo, deviceRepository device.Repository, endpointRepository endpoint.Repository) { - baseRoute := "/v1/graphql" - api := e.Group(baseRoute) - - graphqlHandler := handler.NewDefaultServer( - generated.NewExecutableSchema( - generated.Config{Resolvers: &graph.Resolver{ - DeviceRepository: deviceRepository, - EndpointRepository: endpointRepository, - }}, - ), - ) - - api.POST("/query", func(c echo.Context) error { - graphqlHandler.ServeHTTP(c.Response(), c.Request()) - return nil - }) - - playgroundHandler := playground.Handler("GraphQL", baseRoute+"/query") - api.GET("/playground", func(c echo.Context) error { - playgroundHandler.ServeHTTP(c.Response(), c.Request()) - return nil - }) -} diff --git a/src/routes/routes.go b/src/routes/routes.go deleted file mode 100644 index 9b68b3fb..00000000 --- a/src/routes/routes.go +++ /dev/null @@ -1,64 +0,0 @@ -package routes - -import ( - "github.com/labstack/echo" - "github.com/labstack/echo/middleware" - log "github.com/sirupsen/logrus" - "github.com/spf13/viper" - - "github.com/rna-vt/devicecommander/src/cluster" - "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/endpoint" -) - -// APIService -. -type APIService struct { - Cluster *cluster.Cluster - DeviceRepository device.Repository - EndpointRepository endpoint.Repository - logger *log.Entry -} - -func NewAPIService(cluster *cluster.Cluster, deviceRepository device.Repository, endpointRepository endpoint.Repository) *APIService { - api := APIService{ - Cluster: cluster, - DeviceRepository: deviceRepository, - EndpointRepository: endpointRepository, - logger: log.WithFields(log.Fields{"module": "routes"}), - } - - return &api -} - -// ConfigureRoutes will use Echo to start listening on the appropriate paths. -func (api APIService) ConfigureRoutes(listenURL string, e *echo.Echo) { - // Middleware - e.Use(middleware.Logger()) - e.Use(middleware.Recover()) - - // CORS restricted - // wth GET, PUT, POST or DELETE method. - e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ - AllowOrigins: []string{"*"}, - })) - - frontendRoot := "../frontend/build/" - if viper.GetString("ENV") == "production" { - frontendRoot = "/src/build/" - } - - // Routes - e.Static("/static", frontendRoot+"static") - e.File("/*", frontendRoot+"index.html") - - api.addGraphQLRoutes(e, api.DeviceRepository, api.EndpointRepository) - - api.logger.Info("Configured routes listening on " + listenURL) - - api.logger.Println("*****************************************************") - api.logger.Println("~Rejoice~ The Device Commander Lives Again! ~Rejoice~") - api.logger.Println("*****************************************************") - - // Start server - e.Logger.Fatal(e.Start(listenURL)) -} diff --git a/src/scanner/arp.go b/src/scanner/arp.go index a17cce2a..5c737c25 100644 --- a/src/scanner/arp.go +++ b/src/scanner/arp.go @@ -26,7 +26,7 @@ import ( "github.com/sirupsen/logrus" "github.com/spf13/viper" - "github.com/rna-vt/devicecommander/graph/model" + "github.com/rna-vt/devicecommander/src/device" ) const ( @@ -37,7 +37,7 @@ const ( type ArpScanner struct { LoopDelay int - NewDeviceChan chan model.NewDevice + NewDeviceChan chan device.NewDeviceParams Stop chan struct{} PCAPPort int32 BroadcastResponseWaitSeconds int @@ -45,7 +45,7 @@ type ArpScanner struct { logger *logrus.Entry } -func NewArpScanner(newDeviceChan chan model.NewDevice, stopChan chan struct{}) ArpScanner { +func NewArpScanner(newDeviceChan chan device.NewDeviceParams, stopChan chan struct{}) ArpScanner { return ArpScanner{ LoopDelay: viper.GetInt("ARP_SCANNER_LOOP_DELAY"), NewDeviceChan: newDeviceChan, @@ -178,7 +178,7 @@ func (a *ArpScanner) readARP(handle *pcap.Handle, iface *net.Interface) { tmpMacAddress := net.HardwareAddr(arp.SourceHwAddress).String() ip := net.IP(arp.SourceProtAddress).String() - newDevice := model.NewDevice{ + newDevice := device.NewDeviceParams{ Mac: &tmpMacAddress, Host: ip, Port: a.DefaultPort, diff --git a/src/scanner/scanner.go b/src/scanner/scanner.go index 75f3e290..b52af5c2 100644 --- a/src/scanner/scanner.go +++ b/src/scanner/scanner.go @@ -10,13 +10,12 @@ import ( log "github.com/sirupsen/logrus" - "github.com/rna-vt/devicecommander/graph/model" "github.com/rna-vt/devicecommander/src/device" ) type DeviceResponse struct { Success bool - Device model.NewDevice + Device device.NewDeviceParams } type IPScanResults struct { @@ -59,9 +58,9 @@ func GetLocalAddresses() (IPScanResults, error) { return results, nil } -func ScanIPs(ipSet []net.IP, timeoutSeconds int) ([]model.NewDevice, error) { +func ScanIPs(ipSet []net.IP, timeoutSeconds int) ([]device.NewDeviceParams, error) { logger := getScannerLogger() - deviceList := []model.NewDevice{} + deviceList := []device.NewDeviceParams{} logger.Info("Scan IPs: ", ipSet) @@ -95,7 +94,7 @@ func ProbeHostConcurrent(host string, ch chan<- DeviceResponse, timeoutSeconds i } } -func ProbeHost(host string, timeoutSeconds int) (model.NewDevice, error) { +func ProbeHost(host string, timeoutSeconds int) (device.NewDeviceParams, error) { logger := getScannerLogger() url := "http://" + host + "/registration" logger.Trace("Probing ", host) @@ -105,7 +104,7 @@ func ProbeHost(host string, timeoutSeconds int) (model.NewDevice, error) { } resp, err := client.Get(url) if err != nil { - return model.NewDevice{}, err + return device.NewDeviceParams{}, err } switch resp.StatusCode { @@ -113,7 +112,7 @@ func ProbeHost(host string, timeoutSeconds int) (model.NewDevice, error) { successLogger := logger.WithFields(log.Fields{ "event": "success", }) - dev, err := device.BasicDevice{}.NewDeviceFromRequestBody(resp.Body) + dev, err := device.NewDeviceFromRequestBody(resp.Body) if err != nil { return dev, err } @@ -123,9 +122,9 @@ func ProbeHost(host string, timeoutSeconds int) (model.NewDevice, error) { return dev, nil case http.StatusNotFound: logger.Debug("Host Not Found: " + host) - return model.NewDevice{}, errors.New("host not found " + host) + return device.NewDeviceParams{}, errors.New("host not found " + host) default: logger.Debug("Attempt to register " + host + " resulted in an unexpected response:" + strconv.Itoa(resp.StatusCode)) - return model.NewDevice{}, fmt.Errorf("attempt to register %s resulted in an unexpected response: %d", host, resp.StatusCode) + return device.NewDeviceParams{}, fmt.Errorf("attempt to register %s resulted in an unexpected response: %d", host, resp.StatusCode) } } diff --git a/src/test/utils_test.go b/src/test/utils_test.go deleted file mode 100644 index b306f6d1..00000000 --- a/src/test/utils_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package test - -import ( - "testing" - - "github.com/google/uuid" - "github.com/stretchr/testify/suite" - - "github.com/rna-vt/devicecommander/src/utilities" -) - -type TestSuite struct { - suite.Suite -} - -func (s *TestSuite) SetupSuite() { - utilities.ConfigureEnvironment() -} - -func (s *TestSuite) TestGenerateRandomNewDevice() { - testLength := 3 - testNewDevices := GenerateRandomNewDevices(testLength) - - for _, v := range testNewDevices { - s.Require().NotNil(v, "all of the devices should not be nil") - } - - s.Equal(len(testNewDevices), testLength, "there should be the correct number of devices") -} - -func (s *TestSuite) TestGenerateRandomNewEndpoints() { - testLength := 3 - tmpDeviceID := uuid.New().String() - testNewEndpoints := GenerateRandomNewEndpoints(tmpDeviceID, testLength) - - s.Equal(len(testNewEndpoints), testLength, "there should be the correct number of endpoints") - - testNewEndpoint := testNewEndpoints[0] - - s.Equal(testNewEndpoint.DeviceID, tmpDeviceID, "the NewEndpoint should have the correct DeviceID") -} - -func (s *TestSuite) GenerateRandomNewParameter() { - testLength := 3 - testNewParameters := GenerateRandomNewParameter(testLength) - - s.Equal(len(testNewParameters), testLength, "there should be the correct number of parameters") - - testNewParameter := testNewParameters[0] - - s.Nil(testNewParameter.EndpointID, "the NewParameter's EndpointID should not be initialized") -} - -func (s *TestSuite) GenerateRandomNewParameterForEndpoint() { - testLength := 3 - tmpEndpointID := uuid.New().String() - testNewParameters := GenerateRandomNewParameterForEndpoint(tmpEndpointID, testLength) - - s.Equal(len(testNewParameters), testLength, "there should be the correct number of parameters") - - testNewParameter := testNewParameters[0] - - s.Equal(testNewParameter.EndpointID, tmpEndpointID, "the NewParameter should have the correct EndpointID") -} - -// In order for 'go test' to run this suite, we need to create -// a normal test function and pass our suite to suite.Run. -func TestTestSuite(t *testing.T) { - suite.Run(t, new(TestSuite)) -} From cffc9a964654e12e065313dfc9e5cb37a3849eea Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 17:11:17 -0600 Subject: [PATCH 05/22] make test work --- .../{ => parameter}/ParameterRepository.go | 42 +++++++++---------- src/app/app.go | 2 +- src/device/endpoint.go | 17 ++++---- src/device/{ => parameter}/parameter.go | 2 +- .../{ => parameter}/parameter_repository.go | 2 +- src/device/{ => parameter}/parameter_test.go | 2 +- .../params.go} | 2 +- src/device/parameter/utils.go | 36 ++++++++++++++++ src/device/utils.go | 29 ------------- src/postgres/config.go | 3 +- src/postgres/device/device_repository.go | 3 +- src/postgres/endpoint/endpoint_repository.go | 3 +- .../parameter/parameter_repository.go | 24 +++++------ .../parameter/parameter_repository_test.go | 17 ++++---- src/rest/controllers/device.go | 12 +++--- src/rest/controllers/device_test.go | 30 +++++-------- src/rest/routes/device.go | 2 +- 17 files changed, 116 insertions(+), 112 deletions(-) rename mocks/device/{ => parameter}/ParameterRepository.go (51%) rename src/device/{ => parameter}/parameter.go (98%) rename src/device/{ => parameter}/parameter_repository.go (94%) rename src/device/{ => parameter}/parameter_test.go (99%) rename src/device/{parameter_params.go => parameter/params.go} (96%) create mode 100644 src/device/parameter/utils.go diff --git a/mocks/device/ParameterRepository.go b/mocks/device/parameter/ParameterRepository.go similarity index 51% rename from mocks/device/ParameterRepository.go rename to mocks/device/parameter/ParameterRepository.go index 605f0f71..22be80ae 100644 --- a/mocks/device/ParameterRepository.go +++ b/mocks/device/parameter/ParameterRepository.go @@ -3,7 +3,7 @@ package mocks import ( - device "github.com/rna-vt/devicecommander/src/device" + parameter "github.com/rna-vt/devicecommander/src/device/parameter" mock "github.com/stretchr/testify/mock" ) @@ -13,20 +13,20 @@ type ParameterRepository struct { } // Create provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Create(_a0 device.NewParameterParams) (*device.Parameter, error) { +func (_m *ParameterRepository) Create(_a0 parameter.NewParameterParams) (*parameter.Parameter, error) { ret := _m.Called(_a0) - var r0 *device.Parameter - if rf, ok := ret.Get(0).(func(device.NewParameterParams) *device.Parameter); ok { + var r0 *parameter.Parameter + if rf, ok := ret.Get(0).(func(parameter.NewParameterParams) *parameter.Parameter); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*device.Parameter) + r0 = ret.Get(0).(*parameter.Parameter) } } var r1 error - if rf, ok := ret.Get(1).(func(device.NewParameterParams) error); ok { + if rf, ok := ret.Get(1).(func(parameter.NewParameterParams) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) @@ -36,15 +36,15 @@ func (_m *ParameterRepository) Create(_a0 device.NewParameterParams) (*device.Pa } // Delete provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Delete(_a0 string) (*device.Parameter, error) { +func (_m *ParameterRepository) Delete(_a0 string) (*parameter.Parameter, error) { ret := _m.Called(_a0) - var r0 *device.Parameter - if rf, ok := ret.Get(0).(func(string) *device.Parameter); ok { + var r0 *parameter.Parameter + if rf, ok := ret.Get(0).(func(string) *parameter.Parameter); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*device.Parameter) + r0 = ret.Get(0).(*parameter.Parameter) } } @@ -59,20 +59,20 @@ func (_m *ParameterRepository) Delete(_a0 string) (*device.Parameter, error) { } // Get provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Get(_a0 device.Parameter) ([]*device.Parameter, error) { +func (_m *ParameterRepository) Get(_a0 parameter.Parameter) ([]*parameter.Parameter, error) { ret := _m.Called(_a0) - var r0 []*device.Parameter - if rf, ok := ret.Get(0).(func(device.Parameter) []*device.Parameter); ok { + var r0 []*parameter.Parameter + if rf, ok := ret.Get(0).(func(parameter.Parameter) []*parameter.Parameter); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*device.Parameter) + r0 = ret.Get(0).([]*parameter.Parameter) } } var r1 error - if rf, ok := ret.Get(1).(func(device.Parameter) error); ok { + if rf, ok := ret.Get(1).(func(parameter.Parameter) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) @@ -82,15 +82,15 @@ func (_m *ParameterRepository) Get(_a0 device.Parameter) ([]*device.Parameter, e } // GetAll provides a mock function with given fields: -func (_m *ParameterRepository) GetAll() ([]*device.Parameter, error) { +func (_m *ParameterRepository) GetAll() ([]*parameter.Parameter, error) { ret := _m.Called() - var r0 []*device.Parameter - if rf, ok := ret.Get(0).(func() []*device.Parameter); ok { + var r0 []*parameter.Parameter + if rf, ok := ret.Get(0).(func() []*parameter.Parameter); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]*device.Parameter) + r0 = ret.Get(0).([]*parameter.Parameter) } } @@ -105,11 +105,11 @@ func (_m *ParameterRepository) GetAll() ([]*device.Parameter, error) { } // Update provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Update(_a0 device.UpdateParameterParams) error { +func (_m *ParameterRepository) Update(_a0 parameter.UpdateParameterParams) error { ret := _m.Called(_a0) var r0 error - if rf, ok := ret.Get(0).(func(device.UpdateParameterParams) error); ok { + if rf, ok := ret.Get(0).(func(parameter.UpdateParameterParams) error); ok { r0 = rf(_a0) } else { r0 = ret.Error(0) diff --git a/src/app/app.go b/src/app/app.go index 1a204d82..378e9237 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -15,7 +15,7 @@ type Application struct { Echo *echo.Echo Hostname string DeviceRepository device.Repository - EndpointRepository endpoint.EndpointRepository + EndpointRepository device.EndpointRepository } // SystemInfo returns a stringified version of this api. diff --git a/src/device/endpoint.go b/src/device/endpoint.go index 1b2c3aeb..6d3c3448 100644 --- a/src/device/endpoint.go +++ b/src/device/endpoint.go @@ -2,6 +2,7 @@ package device import ( "github.com/google/uuid" + "github.com/rna-vt/devicecommander/src/device/parameter" log "github.com/sirupsen/logrus" ) @@ -13,13 +14,13 @@ type DeviceEndpoint interface { // layer for interacting with a specific Device's endpoint. type Endpoint struct { // model.Endpoint - ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` - DeviceID uuid.UUID `json:"DeviceID" faker:"uuid_hyphenated"` - Method string `json:"Method"` - Type string `json:"Type" faker:"oneof: get, set"` - Description *string `json:"Description"` - Path *string `json:"Path"` - Parameters []Parameter `json:"Parameters,omitempty"` + ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` + DeviceID uuid.UUID `json:"DeviceID" faker:"uuid_hyphenated"` + Method string `json:"Method"` + Type string `json:"Type" faker:"oneof: get, set"` + Description *string `json:"Description"` + Path *string `json:"Path"` + Parameters []parameter.Parameter `json:"Parameters,omitempty"` Device Device } @@ -36,7 +37,7 @@ func FromNewEndpoint(input NewEndpointParams) (Endpoint, error) { DeviceID: deviceUUID, Type: input.Type, Method: input.Method, - Parameters: []Parameter{}, + Parameters: []parameter.Parameter{}, } if input.Description != nil { diff --git a/src/device/parameter.go b/src/device/parameter/parameter.go similarity index 98% rename from src/device/parameter.go rename to src/device/parameter/parameter.go index 21e1f475..378c848a 100644 --- a/src/device/parameter.go +++ b/src/device/parameter/parameter.go @@ -1,4 +1,4 @@ -package device +package parameter import ( "github.com/google/uuid" diff --git a/src/device/parameter_repository.go b/src/device/parameter/parameter_repository.go similarity index 94% rename from src/device/parameter_repository.go rename to src/device/parameter/parameter_repository.go index 6605fcd2..a2d716cb 100644 --- a/src/device/parameter_repository.go +++ b/src/device/parameter/parameter_repository.go @@ -1,4 +1,4 @@ -package device +package parameter // Repository prototypes the required interfaces for // CRUD actions on a collection of Parameters. diff --git a/src/device/parameter_test.go b/src/device/parameter/parameter_test.go similarity index 99% rename from src/device/parameter_test.go rename to src/device/parameter/parameter_test.go index c69cb2d8..5cc858de 100644 --- a/src/device/parameter_test.go +++ b/src/device/parameter/parameter_test.go @@ -1,4 +1,4 @@ -package device +package parameter import ( "testing" diff --git a/src/device/parameter_params.go b/src/device/parameter/params.go similarity index 96% rename from src/device/parameter_params.go rename to src/device/parameter/params.go index 063f747a..3fa1536a 100644 --- a/src/device/parameter_params.go +++ b/src/device/parameter/params.go @@ -1,4 +1,4 @@ -package device +package parameter type NewParameterParams struct { EndpointID string `json:"EndpointID" faker:"uuid_hyphenated"` diff --git a/src/device/parameter/utils.go b/src/device/parameter/utils.go new file mode 100644 index 00000000..981d8233 --- /dev/null +++ b/src/device/parameter/utils.go @@ -0,0 +1,36 @@ +package parameter + +import ( + "log" + + "github.com/bxcodec/faker/v3" +) + +func GenerateRandomNewParameter(count int) []NewParameterParams { + collection := []NewParameterParams{} + for i := 0; i < count; i++ { + tmpParam := NewParameterParams{} + err := faker.FakeData(&tmpParam) + if err != nil { + log.Fatal(err) + } + + collection = append(collection, tmpParam) + } + return collection +} + +func GenerateRandomNewParameterForEndpoint(endpointID string, count int) []NewParameterParams { + collection := []NewParameterParams{} + for i := 0; i < count; i++ { + tmpParam := NewParameterParams{} + err := faker.FakeData(&tmpParam) + if err != nil { + log.Fatal(err) + } + tmpParam.EndpointID = endpointID + + collection = append(collection, tmpParam) + } + return collection +} diff --git a/src/device/utils.go b/src/device/utils.go index 5e0c2770..c6f65b9b 100644 --- a/src/device/utils.go +++ b/src/device/utils.go @@ -33,32 +33,3 @@ func GenerateRandomNewEndpointParams(deviceID string, count int) []NewEndpointPa } return collection } - -func GenerateRandomNewParameter(count int) []NewParameterParams { - collection := []NewParameterParams{} - for i := 0; i < count; i++ { - tmpParam := NewParameterParams{} - err := faker.FakeData(&tmpParam) - if err != nil { - log.Fatal(err) - } - - collection = append(collection, tmpParam) - } - return collection -} - -func GenerateRandomNewParameterForEndpoint(endpointID string, count int) []NewParameterParams { - collection := []NewParameterParams{} - for i := 0; i < count; i++ { - tmpParam := NewParameterParams{} - err := faker.FakeData(&tmpParam) - if err != nil { - log.Fatal(err) - } - tmpParam.EndpointID = endpointID - - collection = append(collection, tmpParam) - } - return collection -} diff --git a/src/postgres/config.go b/src/postgres/config.go index cd035d2a..dd443139 100644 --- a/src/postgres/config.go +++ b/src/postgres/config.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/parameter" "github.com/spf13/viper" "gorm.io/driver/postgres" "gorm.io/gorm" @@ -50,7 +51,7 @@ func GetDBConnection(config DBConfig) (*gorm.DB, error) { // RunMigration makes sure each of the important models are fully migrated. func RunMigration(db *gorm.DB) error { - if err := db.AutoMigrate(&device.Device{}, &device.Endpoint{}, &device.Parameter{}); err != nil { + if err := db.AutoMigrate(&device.Device{}, &device.Endpoint{}, ¶meter.Parameter{}); err != nil { return err } diff --git a/src/postgres/device/device_repository.go b/src/postgres/device/device_repository.go index 1614d06f..a4f61e1a 100644 --- a/src/postgres/device/device_repository.go +++ b/src/postgres/device/device_repository.go @@ -7,6 +7,7 @@ import ( "gorm.io/gorm/clause" "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/parameter" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -98,7 +99,7 @@ func (r Repository) Delete(id string) (*device.Device, error) { } for _, e := range results[0].Endpoints { - r.DBConnection.Delete(device.Parameter{}, device.Parameter{ + r.DBConnection.Delete(parameter.Parameter{}, parameter.Parameter{ EndpointID: e.ID, }) } diff --git a/src/postgres/endpoint/endpoint_repository.go b/src/postgres/endpoint/endpoint_repository.go index f2dee852..a1feab72 100644 --- a/src/postgres/endpoint/endpoint_repository.go +++ b/src/postgres/endpoint/endpoint_repository.go @@ -7,6 +7,7 @@ import ( "gorm.io/gorm/clause" "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/parameter" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -92,7 +93,7 @@ func (r Repository) Delete(id string) (*device.Endpoint, error) { } toBeDeleted.ID = endUUID - r.DBConnection.Delete(device.Parameter{}, device.Parameter{ + r.DBConnection.Delete(parameter.Parameter{}, parameter.Parameter{ EndpointID: endUUID, }) diff --git a/src/postgres/parameter/parameter_repository.go b/src/postgres/parameter/parameter_repository.go index f94ae9eb..42d7b99d 100644 --- a/src/postgres/parameter/parameter_repository.go +++ b/src/postgres/parameter/parameter_repository.go @@ -8,7 +8,7 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" - "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/parameter" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -48,8 +48,8 @@ func (r Repository) Initialize() (Repository, error) { } // Create on the ParameterRepository creates a new row in the Parameter table in the postgres database. -func (r Repository) Create(newParameterArgs device.NewParameterParams) (*device.Parameter, error) { - newParameter, err := device.FromNewParameter(newParameterArgs) +func (r Repository) Create(newParameterArgs parameter.NewParameterParams) (*parameter.Parameter, error) { + newParameter, err := parameter.FromNewParameter(newParameterArgs) if err != nil { return &newParameter, err } @@ -64,13 +64,13 @@ func (r Repository) Create(newParameterArgs device.NewParameterParams) (*device. } // Update on the ParameterRepository updates a new single row in the Parameter table according to the specified UpdateParameter.ID. -func (r Repository) Update(input device.UpdateParameterParams) error { +func (r Repository) Update(input parameter.UpdateParameterParams) error { parameterID, err := uuid.Parse(input.ID) if err != nil { return err } - end := device.Parameter{ID: parameterID} + end := parameter.Parameter{ID: parameterID} result := r.DBConnection.Session(&gorm.Session{FullSaveAssociations: true}).Model(end).Updates(input) if result.Error != nil { @@ -82,8 +82,8 @@ func (r Repository) Update(input device.UpdateParameterParams) error { } // Delete on the ParameterRepository removes a single row from the Parameter table by the specific ID. -func (r Repository) Delete(id string) (*device.Parameter, error) { - var toBeDeleted device.Parameter +func (r Repository) Delete(id string) (*parameter.Parameter, error) { + var toBeDeleted parameter.Parameter parameterID, err := uuid.Parse(id) if err != nil { @@ -103,7 +103,7 @@ func (r Repository) Delete(id string) (*device.Parameter, error) { toBeDeleted = *results[0] // TODO: Implement soft deletes - r.DBConnection.Delete(device.Parameter{}, toBeDeleted) + r.DBConnection.Delete(parameter.Parameter{}, toBeDeleted) r.logger.Trace("Deleted Parameter " + id) return &toBeDeleted, nil @@ -111,8 +111,8 @@ func (r Repository) Delete(id string) (*device.Parameter, error) { // Get on the ParameterRepository will retrieve all of the rows that match the query. The // associated object (endpoint) will be preloaded for convenience. -func (r Repository) Get(query device.Parameter) ([]*device.Parameter, error) { - Parameters := []*device.Parameter{} +func (r Repository) Get(query parameter.Parameter) ([]*parameter.Parameter, error) { + Parameters := []*parameter.Parameter{} result := r.DBConnection.Preload(clause.Associations).Where(query).Find(&Parameters) if result.Error != nil { return Parameters, result.Error @@ -123,8 +123,8 @@ func (r Repository) Get(query device.Parameter) ([]*device.Parameter, error) { // GetAll on the ParameterRepository will retrieve all of the rows in the Parameter table. The // associated objects (endpoints) will be preloaded for convenience. -func (r Repository) GetAll() ([]*device.Parameter, error) { - Parameters := []*device.Parameter{} +func (r Repository) GetAll() ([]*parameter.Parameter, error) { + Parameters := []*parameter.Parameter{} result := r.DBConnection.Find(&Parameters) if result.Error != nil { return Parameters, result.Error diff --git a/src/postgres/parameter/parameter_repository_test.go b/src/postgres/parameter/parameter_repository_test.go index 1745cc8c..07cb3e24 100644 --- a/src/postgres/parameter/parameter_repository_test.go +++ b/src/postgres/parameter/parameter_repository_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/parameter" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" "github.com/rna-vt/devicecommander/src/postgres/endpoint" @@ -19,10 +20,10 @@ type PostgresParameterRepositorySuite struct { suite.Suite testDevices []device.Device testEndpoints []device.Endpoint - testParameters []device.Parameter + testParameters []parameter.Parameter deviceRepository postgresDevice.Repository endpointRepository endpoint.Repository - parameterRepository device.ParameterRepository + parameterRepository parameter.ParameterRepository } func (s *PostgresParameterRepositorySuite) SetupSuite() { @@ -55,9 +56,9 @@ func (s *PostgresParameterRepositorySuite) SetupSuite() { s.testEndpoints = append(s.testEndpoints, *end) } -func (s *PostgresParameterRepositorySuite) CreateTestParameter() device.Parameter { +func (s *PostgresParameterRepositorySuite) CreateTestParameter() parameter.Parameter { currentTestEndpoint := s.testEndpoints[0] - testParameters := device.GenerateRandomNewParameterForEndpoint(currentTestEndpoint.ID.String(), 1) + testParameters := parameter.GenerateRandomNewParameterForEndpoint(currentTestEndpoint.ID.String(), 1) param, err := s.parameterRepository.Create(testParameters[0]) assert.Nil(s.T(), err, "creating a test parameter should not throw an error") @@ -70,7 +71,7 @@ func (s *PostgresParameterRepositorySuite) CreateTestParameter() device.Paramete func (s *PostgresParameterRepositorySuite) TestGet() { testParameter := s.CreateTestParameter() - results, err := s.parameterRepository.Get(device.Parameter{ + results, err := s.parameterRepository.Get(parameter.Parameter{ ID: testParameter.ID, }) assert.Nil(s.T(), err) @@ -88,7 +89,7 @@ func (s *PostgresParameterRepositorySuite) TestDelete() { assert.Equal(s.T(), deleteResult.ID, testParameter.ID, "the return from a delete should contain the deleted object") - getResults, err := s.parameterRepository.Get(device.Parameter{ + getResults, err := s.parameterRepository.Get(parameter.Parameter{ ID: testParameter.ID, }) assert.Nil(s.T(), err) @@ -100,13 +101,13 @@ func (s *PostgresParameterRepositorySuite) TestUpdate() { testParameter := s.CreateTestParameter() tmpDesc := "Radom test update" - err := s.parameterRepository.Update(device.UpdateParameterParams{ + err := s.parameterRepository.Update(parameter.UpdateParameterParams{ ID: testParameter.ID.String(), Description: &tmpDesc, }) assert.Nil(s.T(), err) - getResults, err := s.parameterRepository.Get(device.Parameter{ + getResults, err := s.parameterRepository.Get(parameter.Parameter{ ID: testParameter.ID, }) assert.Nil(s.T(), err) diff --git a/src/rest/controllers/device.go b/src/rest/controllers/device.go index 7478d271..2ebd9640 100644 --- a/src/rest/controllers/device.go +++ b/src/rest/controllers/device.go @@ -68,12 +68,12 @@ func (controller DeviceController) GetDevice(c echo.Context) error { } func (controller DeviceController) Update(c echo.Context) error { - updateParams := new(device.UpdateDeviceParams) - if err := c.Bind(updateParams); err != nil { + updateParams := device.UpdateDeviceParams{} + if err := c.Bind(&updateParams); err != nil { return err } - err := controller.Repository.Update(*updateParams) + err := controller.Repository.Update(updateParams) if err != nil { return err } @@ -81,8 +81,10 @@ func (controller DeviceController) Update(c echo.Context) error { } func (controller DeviceController) Delete(c echo.Context) error { - log.Info("DEVICE_ID", c.Param("deviceID")) - toDelete, err := controller.Repository.Delete(c.Param("deviceID")) + + deviceID := c.Param("id") + log.Infof("DEVICE_ID='%s'", deviceID) + toDelete, err := controller.Repository.Delete(deviceID) if err != nil { return err } diff --git a/src/rest/controllers/device_test.go b/src/rest/controllers/device_test.go index 060491cf..0950d4b3 100644 --- a/src/rest/controllers/device_test.go +++ b/src/rest/controllers/device_test.go @@ -37,11 +37,13 @@ func NewEchoContext(method, path string, data interface{}) echo.Context { requestByte, _ := json.Marshal(data) requestReader := bytes.NewReader(requestByte) - req, err := http.NewRequest("POST", "/v1/device", requestReader) + req, err := http.NewRequest(method, path, requestReader) if err != nil { logrus.Error(err) } + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + e := echo.New() res := httptest.NewRecorder() return e.NewContext(req, res) @@ -54,10 +56,6 @@ func (s *DeviceControllerSuite) TestCreateDevice() { err := s.controller.Create(NewEchoContext("POST", "/v1/device", newDevices[0])) assert.Nil(s.T(), err) - - s.mockDeviceRepository.AssertCalled(s.T(), "Create", newDevices[0]) - - s.mockDeviceRepository.AssertExpectations(s.T()) } func (s *DeviceControllerSuite) TestGetDevices() { @@ -65,23 +63,19 @@ func (s *DeviceControllerSuite) TestGetDevices() { s.mockDeviceRepository.On("GetAll").Return([]*device.Device{}, nil) err := s.controller.GetAll(NewEchoContext("GET", "/v1/device", nil)) assert.Nil(s.T(), err) - - s.mockDeviceRepository.AssertCalled(s.T(), "GetAll") - - s.mockDeviceRepository.AssertExpectations(s.T()) } func (s *DeviceControllerSuite) TestDeleteDevice() { randomUUID := uuid.New().String() - ctx := NewEchoContext("DELETE", "/v1/device/"+randomUUID, nil) - s.mockDeviceRepository.On("Delete", randomUUID).Return(&device.Device{}, randomUUID) - err := s.controller.Delete(ctx) - assert.Nil(s.T(), err) + ctx := NewEchoContext("DELETE", "/v1/device/:id", nil) - s.mockDeviceRepository.AssertCalled(s.T(), "Delete", randomUUID) + ctx.SetParamNames("id") + ctx.SetParamValues(randomUUID) - s.mockDeviceRepository.AssertExpectations(s.T()) + s.mockDeviceRepository.On("Delete", randomUUID).Return(&device.Device{}, nil) + err := s.controller.Delete(ctx) + assert.Nil(s.T(), err) } func (s *DeviceControllerSuite) TestUpdateDevice() { @@ -95,14 +89,10 @@ func (s *DeviceControllerSuite) TestUpdateDevice() { s.mockDeviceRepository.On("Update", updateInput).Return(nil) err := s.controller.Update(ctx) assert.Nil(s.T(), err) - - s.mockDeviceRepository.AssertCalled(s.T(), "Update", updateInput) - - // s.mockDeviceRepository.AssertExpectations(s.T()) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run. -func TestDeviceControllerTestSuite(t *testing.T) { +func TestDeviceRESTControllerTestSuite(t *testing.T) { suite.Run(t, new(DeviceControllerSuite)) } diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index 4f8d0648..dce6f104 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -15,5 +15,5 @@ func (r DeviceRouter) RegisterRoutes(e *echo.Echo) { api.POST("/", r.DeviceController.Create) api.GET("/", r.DeviceController.GetAll) api.GET("/:id", r.DeviceController.GetDevice) - api.DELETE("/:deviceID", r.DeviceController.GetDevice) + api.DELETE("/:id", r.DeviceController.Delete) } From aa5457aa8723b48655050a14c256eb82196e0983 Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 17:25:29 -0600 Subject: [PATCH 06/22] lint --- .../{ParameterRepository.go => Repository.go} | 14 +++---- src/device/endpoint.go | 9 ++-- src/device/health.go | 2 +- src/device/parameter/parameter_repository.go | 2 +- src/postgres/config.go | 5 ++- .../parameter/parameter_repository_test.go | 5 +-- src/rest/controllers/device.go | 1 - src/rest/controllers/device_test.go | 41 +++++++++++-------- 8 files changed, 43 insertions(+), 36 deletions(-) rename mocks/device/parameter/{ParameterRepository.go => Repository.go} (79%) diff --git a/mocks/device/parameter/ParameterRepository.go b/mocks/device/parameter/Repository.go similarity index 79% rename from mocks/device/parameter/ParameterRepository.go rename to mocks/device/parameter/Repository.go index 22be80ae..886d244d 100644 --- a/mocks/device/parameter/ParameterRepository.go +++ b/mocks/device/parameter/Repository.go @@ -7,13 +7,13 @@ import ( mock "github.com/stretchr/testify/mock" ) -// ParameterRepository is an autogenerated mock type for the ParameterRepository type -type ParameterRepository struct { +// Repository is an autogenerated mock type for the Repository type +type Repository struct { mock.Mock } // Create provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Create(_a0 parameter.NewParameterParams) (*parameter.Parameter, error) { +func (_m *Repository) Create(_a0 parameter.NewParameterParams) (*parameter.Parameter, error) { ret := _m.Called(_a0) var r0 *parameter.Parameter @@ -36,7 +36,7 @@ func (_m *ParameterRepository) Create(_a0 parameter.NewParameterParams) (*parame } // Delete provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Delete(_a0 string) (*parameter.Parameter, error) { +func (_m *Repository) Delete(_a0 string) (*parameter.Parameter, error) { ret := _m.Called(_a0) var r0 *parameter.Parameter @@ -59,7 +59,7 @@ func (_m *ParameterRepository) Delete(_a0 string) (*parameter.Parameter, error) } // Get provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Get(_a0 parameter.Parameter) ([]*parameter.Parameter, error) { +func (_m *Repository) Get(_a0 parameter.Parameter) ([]*parameter.Parameter, error) { ret := _m.Called(_a0) var r0 []*parameter.Parameter @@ -82,7 +82,7 @@ func (_m *ParameterRepository) Get(_a0 parameter.Parameter) ([]*parameter.Parame } // GetAll provides a mock function with given fields: -func (_m *ParameterRepository) GetAll() ([]*parameter.Parameter, error) { +func (_m *Repository) GetAll() ([]*parameter.Parameter, error) { ret := _m.Called() var r0 []*parameter.Parameter @@ -105,7 +105,7 @@ func (_m *ParameterRepository) GetAll() ([]*parameter.Parameter, error) { } // Update provides a mock function with given fields: _a0 -func (_m *ParameterRepository) Update(_a0 parameter.UpdateParameterParams) error { +func (_m *Repository) Update(_a0 parameter.UpdateParameterParams) error { ret := _m.Called(_a0) var r0 error diff --git a/src/device/endpoint.go b/src/device/endpoint.go index 6d3c3448..c793a9a1 100644 --- a/src/device/endpoint.go +++ b/src/device/endpoint.go @@ -2,13 +2,14 @@ package device import ( "github.com/google/uuid" - "github.com/rna-vt/devicecommander/src/device/parameter" log "github.com/sirupsen/logrus" + + "github.com/rna-vt/devicecommander/src/device/parameter" ) -type DeviceEndpoint interface { - Execute(map[string]interface{}) error -} +// type DeviceEndpoint interface { +// Execute(map[string]interface{}) error +// } // DeviceEndpoint implements the Endpoint interface. It provides a functional // layer for interacting with a specific Device's endpoint. diff --git a/src/device/health.go b/src/device/health.go index 644f878e..d26c5638 100644 --- a/src/device/health.go +++ b/src/device/health.go @@ -20,7 +20,7 @@ func (d Device) RunHealthCheck(client Client) error { d.logger.Trace(fmt.Sprintf("device [%s] is not healthy", d.ID.String())) } - d.Failures = d.ProcessHealthCheckResult(result) + _ = d.ProcessHealthCheckResult(result) // TODO: need to cleanup unresponsive nodes somewhere // if d.Unresponsive() { diff --git a/src/device/parameter/parameter_repository.go b/src/device/parameter/parameter_repository.go index a2d716cb..40b5f29b 100644 --- a/src/device/parameter/parameter_repository.go +++ b/src/device/parameter/parameter_repository.go @@ -2,7 +2,7 @@ package parameter // Repository prototypes the required interfaces for // CRUD actions on a collection of Parameters. -type ParameterRepository interface { +type Repository interface { Create(NewParameterParams) (*Parameter, error) Update(UpdateParameterParams) error Delete(string) (*Parameter, error) diff --git a/src/postgres/config.go b/src/postgres/config.go index dd443139..b3beca6a 100644 --- a/src/postgres/config.go +++ b/src/postgres/config.go @@ -3,11 +3,12 @@ package postgres import ( "fmt" - "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/device/parameter" "github.com/spf13/viper" "gorm.io/driver/postgres" "gorm.io/gorm" + + "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/parameter" ) // DBConfig encapsulates the information required for connecting to a database. diff --git a/src/postgres/parameter/parameter_repository_test.go b/src/postgres/parameter/parameter_repository_test.go index 07cb3e24..c5de205f 100644 --- a/src/postgres/parameter/parameter_repository_test.go +++ b/src/postgres/parameter/parameter_repository_test.go @@ -11,7 +11,6 @@ import ( "github.com/rna-vt/devicecommander/src/device/parameter" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" - "github.com/rna-vt/devicecommander/src/postgres/endpoint" postgresEndpoint "github.com/rna-vt/devicecommander/src/postgres/endpoint" "github.com/rna-vt/devicecommander/src/utilities" ) @@ -22,8 +21,8 @@ type PostgresParameterRepositorySuite struct { testEndpoints []device.Endpoint testParameters []parameter.Parameter deviceRepository postgresDevice.Repository - endpointRepository endpoint.Repository - parameterRepository parameter.ParameterRepository + endpointRepository device.EndpointRepository + parameterRepository parameter.Repository } func (s *PostgresParameterRepositorySuite) SetupSuite() { diff --git a/src/rest/controllers/device.go b/src/rest/controllers/device.go index 2ebd9640..81e51f08 100644 --- a/src/rest/controllers/device.go +++ b/src/rest/controllers/device.go @@ -81,7 +81,6 @@ func (controller DeviceController) Update(c echo.Context) error { } func (controller DeviceController) Delete(c echo.Context) error { - deviceID := c.Param("id") log.Infof("DEVICE_ID='%s'", deviceID) toDelete, err := controller.Repository.Delete(deviceID) diff --git a/src/rest/controllers/device_test.go b/src/rest/controllers/device_test.go index 0950d4b3..3d513066 100644 --- a/src/rest/controllers/device_test.go +++ b/src/rest/controllers/device_test.go @@ -10,8 +10,6 @@ import ( "github.com/google/uuid" "github.com/labstack/echo" - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" mocks "github.com/rna-vt/devicecommander/mocks/device" @@ -33,20 +31,24 @@ func (s *DeviceControllerSuite) SetupSuite() { s.ctx = context.Background() } -func NewEchoContext(method, path string, data interface{}) echo.Context { - requestByte, _ := json.Marshal(data) +func NewEchoContext(method, path string, data interface{}) (echo.Context, error) { + requestByte, err := json.Marshal(data) + if err != nil { + return nil, err + } + requestReader := bytes.NewReader(requestByte) req, err := http.NewRequest(method, path, requestReader) if err != nil { - logrus.Error(err) + return nil, err } req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) e := echo.New() res := httptest.NewRecorder() - return e.NewContext(req, res) + return e.NewContext(req, res), nil } func (s *DeviceControllerSuite) TestCreateDevice() { @@ -54,28 +56,32 @@ func (s *DeviceControllerSuite) TestCreateDevice() { s.mockDeviceRepository.On("Create", newDevices[0]).Return(&device.Device{}, nil) - err := s.controller.Create(NewEchoContext("POST", "/v1/device", newDevices[0])) - assert.Nil(s.T(), err) + ctx, err := NewEchoContext("POST", "/v1/device", newDevices[0]) + s.Nil(err) + err = s.controller.Create(ctx) + s.Nil(err) } func (s *DeviceControllerSuite) TestGetDevices() { - s.mockDeviceRepository.On("GetAll").Return([]*device.Device{}, nil) - err := s.controller.GetAll(NewEchoContext("GET", "/v1/device", nil)) - assert.Nil(s.T(), err) + ctx, err := NewEchoContext("GET", "/v1/device", nil) + s.Nil(err) + err = s.controller.GetAll(ctx) + s.Nil(err) } func (s *DeviceControllerSuite) TestDeleteDevice() { randomUUID := uuid.New().String() - ctx := NewEchoContext("DELETE", "/v1/device/:id", nil) + ctx, err := NewEchoContext("DELETE", "/v1/device/:id", nil) + s.Nil(err) ctx.SetParamNames("id") ctx.SetParamValues(randomUUID) s.mockDeviceRepository.On("Delete", randomUUID).Return(&device.Device{}, nil) - err := s.controller.Delete(ctx) - assert.Nil(s.T(), err) + err = s.controller.Delete(ctx) + s.Nil(err) } func (s *DeviceControllerSuite) TestUpdateDevice() { @@ -84,11 +90,12 @@ func (s *DeviceControllerSuite) TestUpdateDevice() { ID: "uuid.string", Name: &tmpName, } - ctx := NewEchoContext("POST", "/v1/device", updateInput) + ctx, err := NewEchoContext("POST", "/v1/device", updateInput) + s.Nil(err) s.mockDeviceRepository.On("Update", updateInput).Return(nil) - err := s.controller.Update(ctx) - assert.Nil(s.T(), err) + err = s.controller.Update(ctx) + s.Nil(err) } // In order for 'go test' to run this suite, we need to create From 3d8b98fbca3314677948fec64d187e66c613b627 Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 17:42:47 -0600 Subject: [PATCH 07/22] split endpoint into its own mod, nest device->endpoint->parameter mods accoding to data struct --- mocks/device/DeviceEndpoint.go | 24 ---- mocks/device/EndpointRepository.go | 119 ------------------ .../{ => endpoint}/parameter/Repository.go | 2 +- src/app/app.go | 3 +- src/device/device.go | 5 +- src/device/{ => endpoint}/endpoint.go | 13 +- src/device/{ => endpoint}/endpoint_test.go | 2 +- .../{ => endpoint}/parameter/parameter.go | 0 .../parameter/parameter_repository.go | 0 .../parameter/parameter_test.go | 0 src/device/{ => endpoint}/parameter/params.go | 0 src/device/{ => endpoint}/parameter/utils.go | 0 .../params.go} | 2 +- .../repository.go} | 4 +- src/device/endpoint/utils.go | 22 ++++ src/device/utils.go | 15 --- src/postgres/config.go | 5 +- src/postgres/device/device_repository.go | 5 +- src/postgres/endpoint/endpoint_repository.go | 26 ++-- .../endpoint/endpoint_repository_test.go | 20 +-- .../parameter/parameter_repository.go | 2 +- .../parameter/parameter_repository_test.go | 9 +- 22 files changed, 69 insertions(+), 209 deletions(-) delete mode 100644 mocks/device/DeviceEndpoint.go delete mode 100644 mocks/device/EndpointRepository.go rename mocks/device/{ => endpoint}/parameter/Repository.go (97%) rename src/device/{ => endpoint}/endpoint.go (81%) rename src/device/{ => endpoint}/endpoint_test.go (98%) rename src/device/{ => endpoint}/parameter/parameter.go (100%) rename src/device/{ => endpoint}/parameter/parameter_repository.go (100%) rename src/device/{ => endpoint}/parameter/parameter_test.go (100%) rename src/device/{ => endpoint}/parameter/params.go (100%) rename src/device/{ => endpoint}/parameter/utils.go (100%) rename src/device/{endpoint_params.go => endpoint/params.go} (96%) rename src/device/{endpoint_repository.go => endpoint/repository.go} (85%) create mode 100644 src/device/endpoint/utils.go diff --git a/mocks/device/DeviceEndpoint.go b/mocks/device/DeviceEndpoint.go deleted file mode 100644 index 6149e93c..00000000 --- a/mocks/device/DeviceEndpoint.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by mockery v2.9.4. DO NOT EDIT. - -package mocks - -import mock "github.com/stretchr/testify/mock" - -// DeviceEndpoint is an autogenerated mock type for the DeviceEndpoint type -type DeviceEndpoint struct { - mock.Mock -} - -// Execute provides a mock function with given fields: _a0 -func (_m *DeviceEndpoint) Execute(_a0 map[string]interface{}) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(map[string]interface{}) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} diff --git a/mocks/device/EndpointRepository.go b/mocks/device/EndpointRepository.go deleted file mode 100644 index ab16b5f6..00000000 --- a/mocks/device/EndpointRepository.go +++ /dev/null @@ -1,119 +0,0 @@ -// Code generated by mockery v2.9.4. DO NOT EDIT. - -package mocks - -import ( - device "github.com/rna-vt/devicecommander/src/device" - mock "github.com/stretchr/testify/mock" -) - -// EndpointRepository is an autogenerated mock type for the EndpointRepository type -type EndpointRepository struct { - mock.Mock -} - -// Create provides a mock function with given fields: _a0 -func (_m *EndpointRepository) Create(_a0 device.NewEndpointParams) (*device.Endpoint, error) { - ret := _m.Called(_a0) - - var r0 *device.Endpoint - if rf, ok := ret.Get(0).(func(device.NewEndpointParams) *device.Endpoint); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*device.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(device.NewEndpointParams) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Delete provides a mock function with given fields: _a0 -func (_m *EndpointRepository) Delete(_a0 string) (*device.Endpoint, error) { - ret := _m.Called(_a0) - - var r0 *device.Endpoint - if rf, ok := ret.Get(0).(func(string) *device.Endpoint); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*device.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Get provides a mock function with given fields: _a0 -func (_m *EndpointRepository) Get(_a0 device.Endpoint) ([]*device.Endpoint, error) { - ret := _m.Called(_a0) - - var r0 []*device.Endpoint - if rf, ok := ret.Get(0).(func(device.Endpoint) []*device.Endpoint); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]*device.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(device.Endpoint) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetAll provides a mock function with given fields: -func (_m *EndpointRepository) GetAll() ([]*device.Endpoint, error) { - ret := _m.Called() - - var r0 []*device.Endpoint - if rf, ok := ret.Get(0).(func() []*device.Endpoint); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]*device.Endpoint) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Update provides a mock function with given fields: _a0 -func (_m *EndpointRepository) Update(_a0 device.UpdateEndpointParams) error { - ret := _m.Called(_a0) - - var r0 error - if rf, ok := ret.Get(0).(func(device.UpdateEndpointParams) error); ok { - r0 = rf(_a0) - } else { - r0 = ret.Error(0) - } - - return r0 -} diff --git a/mocks/device/parameter/Repository.go b/mocks/device/endpoint/parameter/Repository.go similarity index 97% rename from mocks/device/parameter/Repository.go rename to mocks/device/endpoint/parameter/Repository.go index 886d244d..16e55f47 100644 --- a/mocks/device/parameter/Repository.go +++ b/mocks/device/endpoint/parameter/Repository.go @@ -3,7 +3,7 @@ package mocks import ( - parameter "github.com/rna-vt/devicecommander/src/device/parameter" + parameter "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" mock "github.com/stretchr/testify/mock" ) diff --git a/src/app/app.go b/src/app/app.go index 378e9237..831b9672 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -6,6 +6,7 @@ import ( "github.com/rna-vt/devicecommander/src/cluster" "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/endpoint" "github.com/rna-vt/devicecommander/src/rest/routes" ) @@ -15,7 +16,7 @@ type Application struct { Echo *echo.Echo Hostname string DeviceRepository device.Repository - EndpointRepository device.EndpointRepository + EndpointRepository endpoint.Repository } // SystemInfo returns a stringified version of this api. diff --git a/src/device/device.go b/src/device/device.go index 34d51167..ffb65605 100644 --- a/src/device/device.go +++ b/src/device/device.go @@ -6,6 +6,7 @@ import ( "io" "github.com/google/uuid" + "github.com/rna-vt/devicecommander/src/device/endpoint" log "github.com/sirupsen/logrus" "github.com/spf13/viper" ) @@ -38,7 +39,7 @@ func FromNewDevice(newDeviceArgs NewDeviceParams) Device { ID: uuid.New(), Host: newDeviceArgs.Host, Port: newDeviceArgs.Port, - Endpoints: []Endpoint{}, + Endpoints: []endpoint.Endpoint{}, } if newDeviceArgs.Mac != nil { @@ -88,7 +89,7 @@ type Device struct { // a list of endpoints available for quering on a device. // required: false - Endpoints []Endpoint `json:"Endpoints" faker:"-"` + Endpoints []endpoint.Endpoint `json:"Endpoints" faker:"-"` logger *log.Entry } diff --git a/src/device/endpoint.go b/src/device/endpoint/endpoint.go similarity index 81% rename from src/device/endpoint.go rename to src/device/endpoint/endpoint.go index c793a9a1..9bda9f61 100644 --- a/src/device/endpoint.go +++ b/src/device/endpoint/endpoint.go @@ -1,10 +1,10 @@ -package device +package endpoint import ( "github.com/google/uuid" log "github.com/sirupsen/logrus" - "github.com/rna-vt/devicecommander/src/device/parameter" + "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" ) // type DeviceEndpoint interface { @@ -22,7 +22,6 @@ type Endpoint struct { Description *string `json:"Description"` Path *string `json:"Path"` Parameters []parameter.Parameter `json:"Parameters,omitempty"` - Device Device } // FromNewEndpoint generates an Endpoint from a NewEndpoint with the correctly @@ -52,11 +51,3 @@ func FromNewEndpoint(input NewEndpointParams) (Endpoint, error) { func NewDeviceEndpoint() *Endpoint { return &Endpoint{} } - -// Execute carries out the action associated with the Device's endpoint -// by communicating with the device. -func (e Endpoint) Execute(map[string]interface{}) error { - log.Println(e.Method) - log.Println(e.Device.URL()) - return nil -} diff --git a/src/device/endpoint_test.go b/src/device/endpoint/endpoint_test.go similarity index 98% rename from src/device/endpoint_test.go rename to src/device/endpoint/endpoint_test.go index ae64953f..d9574a5b 100644 --- a/src/device/endpoint_test.go +++ b/src/device/endpoint/endpoint_test.go @@ -1,4 +1,4 @@ -package device +package endpoint import ( "testing" diff --git a/src/device/parameter/parameter.go b/src/device/endpoint/parameter/parameter.go similarity index 100% rename from src/device/parameter/parameter.go rename to src/device/endpoint/parameter/parameter.go diff --git a/src/device/parameter/parameter_repository.go b/src/device/endpoint/parameter/parameter_repository.go similarity index 100% rename from src/device/parameter/parameter_repository.go rename to src/device/endpoint/parameter/parameter_repository.go diff --git a/src/device/parameter/parameter_test.go b/src/device/endpoint/parameter/parameter_test.go similarity index 100% rename from src/device/parameter/parameter_test.go rename to src/device/endpoint/parameter/parameter_test.go diff --git a/src/device/parameter/params.go b/src/device/endpoint/parameter/params.go similarity index 100% rename from src/device/parameter/params.go rename to src/device/endpoint/parameter/params.go diff --git a/src/device/parameter/utils.go b/src/device/endpoint/parameter/utils.go similarity index 100% rename from src/device/parameter/utils.go rename to src/device/endpoint/parameter/utils.go diff --git a/src/device/endpoint_params.go b/src/device/endpoint/params.go similarity index 96% rename from src/device/endpoint_params.go rename to src/device/endpoint/params.go index 6cbe970a..e84e9737 100644 --- a/src/device/endpoint_params.go +++ b/src/device/endpoint/params.go @@ -1,4 +1,4 @@ -package device +package endpoint type NewEndpointParams struct { DeviceID string `json:"DeviceID" faker:"uuid_hyphenated"` diff --git a/src/device/endpoint_repository.go b/src/device/endpoint/repository.go similarity index 85% rename from src/device/endpoint_repository.go rename to src/device/endpoint/repository.go index 6f41f82b..42382076 100644 --- a/src/device/endpoint_repository.go +++ b/src/device/endpoint/repository.go @@ -1,8 +1,8 @@ -package device +package endpoint // Repository prototypes the required interfaces for CRUD // management of a collection of Endpoints. -type EndpointRepository interface { +type Repository interface { Create(NewEndpointParams) (*Endpoint, error) Update(UpdateEndpointParams) error Delete(string) (*Endpoint, error) diff --git a/src/device/endpoint/utils.go b/src/device/endpoint/utils.go new file mode 100644 index 00000000..5a485e10 --- /dev/null +++ b/src/device/endpoint/utils.go @@ -0,0 +1,22 @@ +package endpoint + +import ( + "log" + + "github.com/bxcodec/faker/v3" +) + +func GenerateRandomNewEndpointParams(deviceID string, count int) []NewEndpointParams { + collection := []NewEndpointParams{} + for i := 0; i < count; i++ { + tmpEndpoint := NewEndpointParams{} + err := faker.FakeData(&tmpEndpoint) + if err != nil { + log.Fatal(err) + } + + tmpEndpoint.DeviceID = deviceID + collection = append(collection, tmpEndpoint) + } + return collection +} diff --git a/src/device/utils.go b/src/device/utils.go index c6f65b9b..8a0fb006 100644 --- a/src/device/utils.go +++ b/src/device/utils.go @@ -18,18 +18,3 @@ func GenerateRandomNewDeviceParams(count int) []NewDeviceParams { } return collection } - -func GenerateRandomNewEndpointParams(deviceID string, count int) []NewEndpointParams { - collection := []NewEndpointParams{} - for i := 0; i < count; i++ { - tmpEndpoint := NewEndpointParams{} - err := faker.FakeData(&tmpEndpoint) - if err != nil { - log.Fatal(err) - } - - tmpEndpoint.DeviceID = deviceID - collection = append(collection, tmpEndpoint) - } - return collection -} diff --git a/src/postgres/config.go b/src/postgres/config.go index b3beca6a..9ae2899c 100644 --- a/src/postgres/config.go +++ b/src/postgres/config.go @@ -8,7 +8,8 @@ import ( "gorm.io/gorm" "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/device/parameter" + "github.com/rna-vt/devicecommander/src/device/endpoint" + "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" ) // DBConfig encapsulates the information required for connecting to a database. @@ -52,7 +53,7 @@ func GetDBConnection(config DBConfig) (*gorm.DB, error) { // RunMigration makes sure each of the important models are fully migrated. func RunMigration(db *gorm.DB) error { - if err := db.AutoMigrate(&device.Device{}, &device.Endpoint{}, ¶meter.Parameter{}); err != nil { + if err := db.AutoMigrate(&device.Device{}, &endpoint.Endpoint{}, ¶meter.Parameter{}); err != nil { return err } diff --git a/src/postgres/device/device_repository.go b/src/postgres/device/device_repository.go index a4f61e1a..27691385 100644 --- a/src/postgres/device/device_repository.go +++ b/src/postgres/device/device_repository.go @@ -7,7 +7,8 @@ import ( "gorm.io/gorm/clause" "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/device/parameter" + "github.com/rna-vt/devicecommander/src/device/endpoint" + "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -104,7 +105,7 @@ func (r Repository) Delete(id string) (*device.Device, error) { }) } - r.DBConnection.Delete(device.Endpoint{}, device.Endpoint{ + r.DBConnection.Delete(endpoint.Endpoint{}, endpoint.Endpoint{ DeviceID: uid, }) diff --git a/src/postgres/endpoint/endpoint_repository.go b/src/postgres/endpoint/endpoint_repository.go index a1feab72..1cc41ddb 100644 --- a/src/postgres/endpoint/endpoint_repository.go +++ b/src/postgres/endpoint/endpoint_repository.go @@ -6,8 +6,8 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" - "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/device/parameter" + "github.com/rna-vt/devicecommander/src/device/endpoint" + "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" "github.com/rna-vt/devicecommander/src/postgres" ) @@ -47,8 +47,8 @@ func (r Repository) Initialize() (Repository, error) { return r, nil } -func (r Repository) Create(newDeviceArgs device.NewEndpointParams) (*device.Endpoint, error) { - newEndpoint, err := device.FromNewEndpoint(newDeviceArgs) +func (r Repository) Create(newDeviceArgs endpoint.NewEndpointParams) (*endpoint.Endpoint, error) { + newEndpoint, err := endpoint.FromNewEndpoint(newDeviceArgs) if err != nil { return &newEndpoint, err } @@ -62,13 +62,13 @@ func (r Repository) Create(newDeviceArgs device.NewEndpointParams) (*device.Endp return &newEndpoint, nil } -func (r Repository) Update(input device.UpdateEndpointParams) error { +func (r Repository) Update(input endpoint.UpdateEndpointParams) error { id, err := uuid.Parse(input.ID) if err != nil { return err } - end := device.Endpoint{ID: id} + end := endpoint.Endpoint{ID: id} result := r.DBConnection.Model(end).Updates(input) if result.Error != nil { @@ -85,8 +85,8 @@ func (r Repository) Update(input device.UpdateEndpointParams) error { // Delete on the EndpointRepository removes a single row from the Endpoint table by the // specific ID AND all of the Parameters associated with the EndpointID. -func (r Repository) Delete(id string) (*device.Endpoint, error) { - var toBeDeleted device.Endpoint +func (r Repository) Delete(id string) (*endpoint.Endpoint, error) { + var toBeDeleted endpoint.Endpoint endUUID, err := uuid.Parse(id) if err != nil { return &toBeDeleted, err @@ -97,7 +97,7 @@ func (r Repository) Delete(id string) (*device.Endpoint, error) { EndpointID: endUUID, }) - r.DBConnection.Delete(device.Endpoint{}, toBeDeleted) + r.DBConnection.Delete(endpoint.Endpoint{}, toBeDeleted) r.logger.Debug("Deleted endpoint " + id) return &toBeDeleted, nil @@ -105,8 +105,8 @@ func (r Repository) Delete(id string) (*device.Endpoint, error) { // Get on the EndpointRepository will retrieve all of the rows that match the query. The // associated objects (parameters) will be preloaded for convenience. -func (r Repository) Get(query device.Endpoint) ([]*device.Endpoint, error) { - endpoints := []*device.Endpoint{} +func (r Repository) Get(query endpoint.Endpoint) ([]*endpoint.Endpoint, error) { + endpoints := []*endpoint.Endpoint{} result := r.DBConnection.Preload(clause.Associations).Where(query).Find(&endpoints) if result.Error != nil { return endpoints, result.Error @@ -115,8 +115,8 @@ func (r Repository) Get(query device.Endpoint) ([]*device.Endpoint, error) { return endpoints, nil } -func (r Repository) GetAll() ([]*device.Endpoint, error) { - endpoints := []*device.Endpoint{} +func (r Repository) GetAll() ([]*endpoint.Endpoint, error) { + endpoints := []*endpoint.Endpoint{} result := r.DBConnection.Preload(clause.Associations).Find(&endpoints) if result.Error != nil { return endpoints, result.Error diff --git a/src/postgres/endpoint/endpoint_repository_test.go b/src/postgres/endpoint/endpoint_repository_test.go index 618432ad..59aec987 100644 --- a/src/postgres/endpoint/endpoint_repository_test.go +++ b/src/postgres/endpoint/endpoint_repository_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/rna-vt/devicecommander/src/device" + "github.com/rna-vt/devicecommander/src/device/endpoint" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" "github.com/rna-vt/devicecommander/src/utilities" @@ -17,8 +18,8 @@ import ( type PostgresEndpointRepositorySuite struct { suite.Suite testDevices []device.Device - testEndpoints []device.Endpoint - endpointRepository device.EndpointRepository + testEndpoints []endpoint.Endpoint + endpointRepository endpoint.Repository deviceRepository device.Repository } @@ -42,14 +43,13 @@ func (s *PostgresEndpointRepositorySuite) SetupSuite() { s.testDevices = append(s.testDevices, *dev) } -func (s *PostgresEndpointRepositorySuite) CreateTestEndpoint() device.Endpoint { - testEndpoints := device.GenerateRandomNewEndpointParams(s.testDevices[0].ID.String(), 1) +func (s *PostgresEndpointRepositorySuite) CreateTestEndpoint() endpoint.Endpoint { + testEndpoints := endpoint.GenerateRandomNewEndpointParams(s.testDevices[0].ID.String(), 1) testEndpoint := testEndpoints[0] end, err := s.endpointRepository.Create(testEndpoint) assert.Nil(s.T(), err) s.testDevices[0].Endpoints = nil - end.Device = s.testDevices[0] s.testEndpoints = append(s.testEndpoints, *end) @@ -59,7 +59,7 @@ func (s *PostgresEndpointRepositorySuite) CreateTestEndpoint() device.Endpoint { func (s *PostgresEndpointRepositorySuite) TestGet() { testEndpoint := s.CreateTestEndpoint() - results, err := s.endpointRepository.Get(device.Endpoint{ + results, err := s.endpointRepository.Get(endpoint.Endpoint{ ID: testEndpoint.ID, }) assert.Nil(s.T(), err) @@ -82,7 +82,7 @@ func (s *PostgresEndpointRepositorySuite) TestDelete() { assert.Equal(s.T(), deleteResult.ID, testEndpoint.ID, "the return from a delete should contain the deleted object") - getResults, err := s.endpointRepository.Get(device.Endpoint{ + getResults, err := s.endpointRepository.Get(endpoint.Endpoint{ ID: testEndpoint.ID, }) assert.Nil(s.T(), err) @@ -96,13 +96,13 @@ func (s *PostgresEndpointRepositorySuite) TestUpdate() { testEndpoint := s.CreateTestEndpoint() tmpDesc := "update random test" - err := s.endpointRepository.Update(device.UpdateEndpointParams{ + err := s.endpointRepository.Update(endpoint.UpdateEndpointParams{ ID: testEndpoint.ID.String(), Description: &tmpDesc, }) assert.Nil(s.T(), err) - getResults, err := s.endpointRepository.Get(device.Endpoint{ + getResults, err := s.endpointRepository.Get(endpoint.Endpoint{ ID: testEndpoint.ID, }) assert.Nil(s.T(), err) @@ -115,7 +115,7 @@ func (s *PostgresEndpointRepositorySuite) TestUpdate() { func (s *PostgresEndpointRepositorySuite) TestUpdateNonExistent() { tmpDesc := "non existent random test" tmpUUID := uuid.New() - err := s.endpointRepository.Update(device.UpdateEndpointParams{ + err := s.endpointRepository.Update(endpoint.UpdateEndpointParams{ ID: tmpUUID.String(), Description: &tmpDesc, }) diff --git a/src/postgres/parameter/parameter_repository.go b/src/postgres/parameter/parameter_repository.go index 42d7b99d..ef0d773e 100644 --- a/src/postgres/parameter/parameter_repository.go +++ b/src/postgres/parameter/parameter_repository.go @@ -8,7 +8,7 @@ import ( "gorm.io/gorm" "gorm.io/gorm/clause" - "github.com/rna-vt/devicecommander/src/device/parameter" + "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" "github.com/rna-vt/devicecommander/src/postgres" ) diff --git a/src/postgres/parameter/parameter_repository_test.go b/src/postgres/parameter/parameter_repository_test.go index c5de205f..fa816eb1 100644 --- a/src/postgres/parameter/parameter_repository_test.go +++ b/src/postgres/parameter/parameter_repository_test.go @@ -8,7 +8,8 @@ import ( "github.com/stretchr/testify/suite" "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/device/parameter" + "github.com/rna-vt/devicecommander/src/device/endpoint" + "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" postgresEndpoint "github.com/rna-vt/devicecommander/src/postgres/endpoint" @@ -18,10 +19,10 @@ import ( type PostgresParameterRepositorySuite struct { suite.Suite testDevices []device.Device - testEndpoints []device.Endpoint + testEndpoints []endpoint.Endpoint testParameters []parameter.Parameter deviceRepository postgresDevice.Repository - endpointRepository device.EndpointRepository + endpointRepository endpoint.Repository parameterRepository parameter.Repository } @@ -46,7 +47,7 @@ func (s *PostgresParameterRepositorySuite) SetupSuite() { dev, err := s.deviceRepository.Create(newDevices[0]) assert.Nil(s.T(), err) - testEndpoint := device.GenerateRandomNewEndpointParams(dev.ID.String(), 1) + testEndpoint := endpoint.GenerateRandomNewEndpointParams(dev.ID.String(), 1) end, err := s.endpointRepository.Create(testEndpoint[0]) assert.Nil(s.T(), err) From d3222de2b34ee2fd3a17893e6fe9935d18565135 Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 17:45:17 -0600 Subject: [PATCH 08/22] remove rpc musings --- src/rpc/json.go | 12 ------------ src/rpc/method/device.go | 11 ----------- 2 files changed, 23 deletions(-) delete mode 100644 src/rpc/json.go delete mode 100644 src/rpc/method/device.go diff --git a/src/rpc/json.go b/src/rpc/json.go deleted file mode 100644 index 945f2d3a..00000000 --- a/src/rpc/json.go +++ /dev/null @@ -1,12 +0,0 @@ -package rpc - -type JSONRPC struct { - // example: 1.0 - Version string `json:"jsonrpc"` - - // example: 1 - ID int `json:"id"` - - // example: doMethod - Method string `json:"method"` -} diff --git a/src/rpc/method/device.go b/src/rpc/method/device.go deleted file mode 100644 index 01488b91..00000000 --- a/src/rpc/method/device.go +++ /dev/null @@ -1,11 +0,0 @@ -package method - -import "github.com/rna-vt/devicecommander/src/rpc" - -type GetDevicePayload struct { - rpc.JSONRPC - // example: getDevice - Method string `json:"method"` - // example: 705e4dcb-3ecd-24f3-3a35-3e926e4bded5 - Params string `json:"params"` -} From a1e341c092379ccde5a54c85483324303a901aa5 Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 17:51:42 -0600 Subject: [PATCH 09/22] remove weird swagger docs models --- docs/swagger.json | 196 +------------------------------------ src/device/device.go | 3 +- src/docs/device_swagger.go | 25 ----- src/docs/docs.go | 24 ----- 4 files changed, 3 insertions(+), 245 deletions(-) delete mode 100644 src/docs/device_swagger.go delete mode 100644 src/docs/docs.go diff --git a/docs/swagger.json b/docs/swagger.json index 0a3d3781..92bde890 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1,198 +1,4 @@ { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http" - ], "swagger": "2.0", - "info": { - "description": "DeviceCommander API documentation.", - "title": "DeviceCommander.", - "version": "1.0.0" - }, - "host": "device-commander.rna-vt.com", - "basePath": "/", - "paths": { - "/device": { - "post": { - "summary": "Get information about a single device.", - "operationId": "idOfDevice", - "parameters": [ - { - "description": "This text will appear as description of your request body.", - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/GetDevicePayload" - } - } - ], - "responses": { - "200": { - "$ref": "#/responses/deviceResponse" - } - } - } - } - }, - "definitions": { - "Device": { - "description": "ID -- the serial number of the connecting device\nName - Optional Device Nickname\nDescription - Optional text describing this device\nHost - Device Api Host\nPort - Device Api Port. Set to 443 for https", - "type": "object", - "title": "Device -- a compliant physical component.", - "required": [ - "ID", - "MAC", - "Host", - "Port" - ], - "properties": { - "Active": { - "description": "a flag representing the responsiveness of the device.", - "type": "boolean" - }, - "Description": { - "description": "the description of the device.", - "type": "string" - }, - "Endpoints": { - "description": "a list of endpoints available for quering on a device.", - "type": "array", - "items": { - "$ref": "#/definitions/Endpoint" - } - }, - "Failures": { - "description": "the count of failed actions by the device.", - "type": "integer", - "format": "int64" - }, - "Host": { - "description": "the host address of the device.", - "type": "string" - }, - "ID": { - "$ref": "#/definitions/UUID" - }, - "MAC": { - "description": "the MAC address for this device.", - "type": "string" - }, - "Name": { - "description": "the human readable name of the device.", - "type": "string" - }, - "Port": { - "description": "the active port of the device.", - "type": "integer", - "format": "int64" - } - }, - "x-go-package": "github.com/rna-vt/devicecommander/graph/model" - }, - "Endpoint": { - "type": "object", - "properties": { - "Description": { - "type": "string" - }, - "DeviceID": { - "$ref": "#/definitions/UUID" - }, - "ID": { - "$ref": "#/definitions/UUID" - }, - "Method": { - "type": "string" - }, - "Parameters": { - "type": "array", - "items": { - "$ref": "#/definitions/Parameter" - } - }, - "Path": { - "type": "string" - }, - "Type": { - "type": "string" - } - }, - "x-go-package": "github.com/rna-vt/devicecommander/graph/model" - }, - "GetDevicePayload": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64", - "x-go-name": "ID", - "example": 1 - }, - "jsonrpc": { - "type": "string", - "x-go-name": "Version", - "example": "1.0" - }, - "method": { - "type": "string", - "x-go-name": "Method", - "example": "getDevice" - }, - "params": { - "type": "string", - "x-go-name": "Params", - "example": "705e4dcb-3ecd-24f3-3a35-3e926e4bded5" - } - }, - "x-go-package": "github.com/rna-vt/devicecommander/src/rpc/method" - }, - "Parameter": { - "type": "object", - "properties": { - "Description": { - "type": "string" - }, - "EndpointID": { - "$ref": "#/definitions/UUID" - }, - "ID": { - "$ref": "#/definitions/UUID" - }, - "Name": { - "type": "string" - }, - "Type": { - "type": "string" - } - }, - "x-go-package": "github.com/rna-vt/devicecommander/graph/model" - }, - "UUID": { - "description": "A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC\n4122.", - "type": "array", - "items": { - "type": "integer", - "format": "uint8" - }, - "x-go-package": "github.com/google/uuid" - } - }, - "responses": { - "deviceResponse": { - "description": "This text will appear as description of your response body.", - "schema": { - "$ref": "#/definitions/Device" - } - } - }, - "securityDefinitions": { - "basic": { - "type": "basic" - } - } + "paths": {} } \ No newline at end of file diff --git a/src/device/device.go b/src/device/device.go index ffb65605..8bd983ce 100644 --- a/src/device/device.go +++ b/src/device/device.go @@ -6,9 +6,10 @@ import ( "io" "github.com/google/uuid" - "github.com/rna-vt/devicecommander/src/device/endpoint" log "github.com/sirupsen/logrus" "github.com/spf13/viper" + + "github.com/rna-vt/devicecommander/src/device/endpoint" ) type BasicDevice interface { diff --git a/src/docs/device_swagger.go b/src/docs/device_swagger.go deleted file mode 100644 index 25236bdd..00000000 --- a/src/docs/device_swagger.go +++ /dev/null @@ -1,25 +0,0 @@ -package docs - -import ( - "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/rpc/method" -) - -// swagger:route POST /device idOfDevice -// Get information about a single device. -// responses: -// 200: deviceResponse - -// This text will appear as description of your response body. -// swagger:response deviceResponse -type deviceResponseWrapper struct { - // in:body - Body device.Device -} - -// swagger:parameters idOfDevice -type deviceParamsWrapper struct { - // This text will appear as description of your request body. - // in:body - Body method.GetDevicePayload -} diff --git a/src/docs/docs.go b/src/docs/docs.go deleted file mode 100644 index 2d79c085..00000000 --- a/src/docs/docs.go +++ /dev/null @@ -1,24 +0,0 @@ -// Package classification DeviceCommander. -// -// DeviceCommander API documentation. -// -// Schemes: http -// BasePath: / -// Version: 1.0.0 -// Host: device-commander.rna-vt.com -// -// Consumes: -// - application/json -// -// Produces: -// - application/json -// -// Security: -// - basic -// -// SecurityDefinitions: -// basic: -// type: basic -// -// swagger:meta -package docs From ce97db4257f39ac9f2a6c803535ebd95ca8e8391 Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 18:21:05 -0600 Subject: [PATCH 10/22] make device,endpoint,parameter swagger models --- Makefile | 2 +- docs/swagger.json | 149 ++++++++++++++++++++- src/device/device.go | 16 +-- src/device/endpoint/endpoint.go | 14 +- src/device/endpoint/parameter/parameter.go | 3 + src/rest/routes/device.go | 22 +++ 6 files changed, 186 insertions(+), 20 deletions(-) diff --git a/Makefile b/Makefile index 37c3a2f1..fb205b04 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ swagger: check-swagger swagger generate spec --work-dir src -o ./docs/swagger.json --scan-models serve-swagger: check-swagger - swagger serve -F=swagger swagger.yaml + swagger serve -F=swagger docs/swagger.json mock: rm -rf mocks diff --git a/docs/swagger.json b/docs/swagger.json index 92bde890..a60232a8 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1,4 +1,151 @@ { "swagger": "2.0", - "paths": {} + "paths": { + "/v1/device": { + "get": { + "description": "This will show all devices stored in the DB.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http", + "https" + ], + "summary": "Lists all Devices", + "operationId": "getAllDevices", + "responses": { + "200": { + "$ref": "#/responses/someResponse" + }, + "422": { + "$ref": "#/responses/validationError" + }, + "default": { + "$ref": "#/responses/genericError" + } + } + } + } + }, + "definitions": { + "Device": { + "description": "Device is one of the core concepts of this application. A Device represents\na microcontroller that complies with the DeviceCommander standard.", + "type": "object", + "required": [ + "ID", + "MAC", + "Host", + "Port" + ], + "properties": { + "Active": { + "description": "a flag representing the responsiveness of the device.", + "type": "boolean" + }, + "Description": { + "description": "the description of the device.", + "type": "string" + }, + "Endpoints": { + "description": "a list of endpoints available for quering on a device.", + "type": "array", + "items": { + "$ref": "#/definitions/Endpoint" + } + }, + "Failures": { + "description": "the count of failed actions by the device.", + "type": "integer", + "format": "int64" + }, + "Host": { + "description": "the host address of the device.", + "type": "string" + }, + "ID": { + "$ref": "#/definitions/UUID" + }, + "MAC": { + "description": "the MAC address for this device.", + "type": "string" + }, + "Name": { + "description": "the human readable name of the device.", + "type": "string" + }, + "Port": { + "description": "the active port of the device.", + "type": "integer", + "format": "int64" + } + }, + "x-go-package": "github.com/rna-vt/devicecommander/src/device" + }, + "Endpoint": { + "description": "Future possible example endpoints:\n\"on/off\"\n\"set artnet universe\"\n\"set color\"\n\"read temperature\"", + "type": "object", + "title": "An Endpoint is a single api endpoint served and described by the device.", + "properties": { + "Description": { + "type": "string" + }, + "DeviceID": { + "$ref": "#/definitions/UUID" + }, + "ID": { + "$ref": "#/definitions/UUID" + }, + "Method": { + "type": "string" + }, + "Parameters": { + "type": "array", + "items": { + "$ref": "#/definitions/Parameter" + } + }, + "Path": { + "type": "string" + }, + "Type": { + "type": "string" + } + }, + "x-go-package": "github.com/rna-vt/devicecommander/src/device/endpoint" + }, + "Parameter": { + "type": "object", + "title": "A Parameter is used in conjunction with an Endpoint to define a control point for a device.", + "properties": { + "Description": { + "type": "string" + }, + "EndpointID": { + "$ref": "#/definitions/UUID" + }, + "ID": { + "$ref": "#/definitions/UUID" + }, + "Name": { + "type": "string" + }, + "Type": { + "type": "string" + } + }, + "x-go-package": "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" + }, + "UUID": { + "description": "A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC\n4122.", + "type": "array", + "items": { + "type": "integer", + "format": "uint8" + }, + "x-go-package": "github.com/google/uuid" + } + } } \ No newline at end of file diff --git a/src/device/device.go b/src/device/device.go index 8bd983ce..08e6c53c 100644 --- a/src/device/device.go +++ b/src/device/device.go @@ -50,8 +50,10 @@ func FromNewDevice(newDeviceArgs NewDeviceParams) Device { return newDevice } -// Device is a wrapper for the Device model. It aims to provide a helpful -// layer of abstraction away from the gqlgen/postgres models. +// Device is one of the core concepts of this application. A Device represents +// a microcontroller that complies with the DeviceCommander standard. +// +// swagger:model type Device struct { // the UUID for the device. @@ -95,16 +97,6 @@ type Device struct { logger *log.Entry } -// // NewDeviceWrapper creates a new instance of a device.Wrapper. -// func NewDevice(d model.Device) Device { -// dev := Device{ -// Device: &d, -// logger: log.WithFields(log.Fields{"module": "device"}), -// } - -// return dev -// } - // NewDevice creates a barebones new instance of a Device with a host and port. func NewDevice(host string, port int) (Device, error) { dev := Device{ diff --git a/src/device/endpoint/endpoint.go b/src/device/endpoint/endpoint.go index 9bda9f61..d372c85b 100644 --- a/src/device/endpoint/endpoint.go +++ b/src/device/endpoint/endpoint.go @@ -7,12 +7,14 @@ import ( "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" ) -// type DeviceEndpoint interface { -// Execute(map[string]interface{}) error -// } - -// DeviceEndpoint implements the Endpoint interface. It provides a functional -// layer for interacting with a specific Device's endpoint. +// An Endpoint is a single api endpoint served and described by the device. +// Future possible example endpoints: +// * "on/off" +// * "set artnet universe" +// * "set color" +// * "read temperature" +// +// swagger:model type Endpoint struct { // model.Endpoint ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` diff --git a/src/device/endpoint/parameter/parameter.go b/src/device/endpoint/parameter/parameter.go index 378c848a..380569b1 100644 --- a/src/device/endpoint/parameter/parameter.go +++ b/src/device/endpoint/parameter/parameter.go @@ -4,6 +4,9 @@ import ( "github.com/google/uuid" ) +// A Parameter is used in conjunction with an Endpoint to define a control point for a device. +// +// swagger:model type Parameter struct { ID uuid.UUID `json:"ID" faker:"uuid_hyphenated"` EndpointID uuid.UUID `json:"EndpointID" faker:"uuid_hyphenated"` diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index dce6f104..5e35b5df 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -13,7 +13,29 @@ type DeviceRouter struct { func (r DeviceRouter) RegisterRoutes(e *echo.Echo) { api := e.Group("/v1/device") api.POST("/", r.DeviceController.Create) + + // swagger:route GET /v1/device getAllDevices + // + // Lists all Devices + // + // This will show all devices stored in the DB. + // + // Consumes: + // - application/json + // + // Produces: + // - application/json + // + // Schemes: http, https + // + // Deprecated: false + // + // Responses: + // default: genericError + // 200: someResponse + // 422: validationError api.GET("/", r.DeviceController.GetAll) + api.GET("/:id", r.DeviceController.GetDevice) api.DELETE("/:id", r.DeviceController.Delete) } From 4aa0fe41f78ffb85cfff8d54963d86d49fa1eaf5 Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 18:30:32 -0600 Subject: [PATCH 11/22] add swagger go root back --- docs/swagger.json | 40 ++++++++++++++++++++++++++++++++++++++ src/docs/device_swagger.go | 17 ++++++++++++++++ src/docs/docs.go | 24 +++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 src/docs/device_swagger.go create mode 100644 src/docs/docs.go diff --git a/docs/swagger.json b/docs/swagger.json index a60232a8..9d4e71ce 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1,6 +1,33 @@ { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http" + ], "swagger": "2.0", + "info": { + "description": "DeviceCommander API documentation.", + "title": "DeviceCommander.", + "version": "1.0.0" + }, + "host": "device-commander.rna-vt.com", + "basePath": "/", "paths": { + "/device": { + "post": { + "summary": "Get information about a single device.", + "operationId": "idOfDevice", + "responses": { + "200": { + "$ref": "#/responses/deviceResponse" + } + } + } + }, "/v1/device": { "get": { "description": "This will show all devices stored in the DB.", @@ -147,5 +174,18 @@ }, "x-go-package": "github.com/google/uuid" } + }, + "responses": { + "deviceResponse": { + "description": "This text will appear as description of your response body.", + "schema": { + "$ref": "#/definitions/Device" + } + } + }, + "securityDefinitions": { + "basic": { + "type": "basic" + } } } \ No newline at end of file diff --git a/src/docs/device_swagger.go b/src/docs/device_swagger.go new file mode 100644 index 00000000..d43fe3dd --- /dev/null +++ b/src/docs/device_swagger.go @@ -0,0 +1,17 @@ +package docs + +import ( + "github.com/rna-vt/devicecommander/src/device" +) + +// swagger:route POST /device idOfDevice +// Get information about a single device. +// responses: +// 200: deviceResponse + +// This text will appear as description of your response body. +// swagger:response deviceResponse +type deviceResponseWrapper struct { + // in:body + Body device.Device +} diff --git a/src/docs/docs.go b/src/docs/docs.go new file mode 100644 index 00000000..2d79c085 --- /dev/null +++ b/src/docs/docs.go @@ -0,0 +1,24 @@ +// Package classification DeviceCommander. +// +// DeviceCommander API documentation. +// +// Schemes: http +// BasePath: / +// Version: 1.0.0 +// Host: device-commander.rna-vt.com +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// Security: +// - basic +// +// SecurityDefinitions: +// basic: +// type: basic +// +// swagger:meta +package docs From 4921df6f7a4abd945a0250fc513486fc35bd98fc Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 18:38:20 -0600 Subject: [PATCH 12/22] fix docs link to this branch --- docs/index.html | 2 +- docs/swagger.json | 19 ------------------- src/docs/device_swagger.go | 17 ----------------- 3 files changed, 1 insertion(+), 37 deletions(-) delete mode 100644 src/docs/device_swagger.go diff --git a/docs/index.html b/docs/index.html index ba4ba82e..2095f5b1 100644 --- a/docs/index.html +++ b/docs/index.html @@ -6,6 +6,6 @@ Device Commander Docs - + \ No newline at end of file diff --git a/docs/swagger.json b/docs/swagger.json index 9d4e71ce..fcb4b037 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -17,17 +17,6 @@ "host": "device-commander.rna-vt.com", "basePath": "/", "paths": { - "/device": { - "post": { - "summary": "Get information about a single device.", - "operationId": "idOfDevice", - "responses": { - "200": { - "$ref": "#/responses/deviceResponse" - } - } - } - }, "/v1/device": { "get": { "description": "This will show all devices stored in the DB.", @@ -175,14 +164,6 @@ "x-go-package": "github.com/google/uuid" } }, - "responses": { - "deviceResponse": { - "description": "This text will appear as description of your response body.", - "schema": { - "$ref": "#/definitions/Device" - } - } - }, "securityDefinitions": { "basic": { "type": "basic" diff --git a/src/docs/device_swagger.go b/src/docs/device_swagger.go deleted file mode 100644 index d43fe3dd..00000000 --- a/src/docs/device_swagger.go +++ /dev/null @@ -1,17 +0,0 @@ -package docs - -import ( - "github.com/rna-vt/devicecommander/src/device" -) - -// swagger:route POST /device idOfDevice -// Get information about a single device. -// responses: -// 200: deviceResponse - -// This text will appear as description of your response body. -// swagger:response deviceResponse -type deviceResponseWrapper struct { - // in:body - Body device.Device -} From 04d236ed44a5f2d37b8ce25f97a56a6457bbf5da Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 29 Apr 2022 19:15:19 -0600 Subject: [PATCH 13/22] swagger some responses --- docs/swagger.json | 40 ++++++++++++++++++++++++++++++++++++++- src/docs/device.go | 15 +++++++++++++++ src/docs/errors.go | 29 ++++++++++++++++++++++++++++ src/rest/routes/device.go | 2 +- 4 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 src/docs/device.go create mode 100644 src/docs/errors.go diff --git a/docs/swagger.json b/docs/swagger.json index fcb4b037..64535881 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -34,7 +34,7 @@ "operationId": "getAllDevices", "responses": { "200": { - "$ref": "#/responses/someResponse" + "$ref": "#/responses/getAllDeviceResponse" }, "422": { "$ref": "#/responses/validationError" @@ -164,6 +164,44 @@ "x-go-package": "github.com/google/uuid" } }, + "responses": { + "getAllDeviceResponse": { + "description": "GetAllDeviceResponse is a response for the GetAllDevices endpoint.", + "schema": { + "type": "object", + "required": [ + "Devices", + "Message" + ], + "properties": { + "Message": { + "type": "string", + "example": "Expected type string" + } + } + } + }, + "validationError": { + "description": "A ValidationError is an error that is used when the required input fails validation.", + "schema": { + "type": "object", + "required": [ + "Message" + ], + "properties": { + "FieldName": { + "description": "An optional field name to which this validation applies", + "type": "string" + }, + "Message": { + "description": "The validation message", + "type": "string", + "example": "Expected type int" + } + } + } + } + }, "securityDefinitions": { "basic": { "type": "basic" diff --git a/src/docs/device.go b/src/docs/device.go new file mode 100644 index 00000000..d18b5640 --- /dev/null +++ b/src/docs/device.go @@ -0,0 +1,15 @@ +package docs + +import "github.com/rna-vt/devicecommander/src/device" + +// GetAllDeviceResponse is a response for the GetAllDevices endpoint. +// swagger:response getAllDeviceResponse +type GetAllDeviceResponse struct { + // The response contains an array of devices. + // in: body + Body struct { + // Required: true + // Example: Expected type []device.Device + Devices []device.Device + } +} diff --git a/src/docs/errors.go b/src/docs/errors.go new file mode 100644 index 00000000..26dffd7b --- /dev/null +++ b/src/docs/errors.go @@ -0,0 +1,29 @@ +package docs + +// GetAllDeviceResponse is a response for the GetAllDevices endpoint. +// swagger:response getAllDeviceResponse +type GenericError struct { + // A Generic error response + // in: body + Body struct { + // Required: true + // Example: Expected type string + Message string + } +} + +// A ValidationError is an error that is used when the required input fails validation. +// swagger:response validationError +type ValidationError struct { + // The error message + // in: body + Body struct { + // The validation message + // + // Required: true + // Example: Expected type int + Message string + // An optional field name to which this validation applies + FieldName string + } +} diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index 5e35b5df..ff9f7003 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -32,7 +32,7 @@ func (r DeviceRouter) RegisterRoutes(e *echo.Echo) { // // Responses: // default: genericError - // 200: someResponse + // 200: getAllDeviceResponse // 422: validationError api.GET("/", r.DeviceController.GetAll) From 8125a7ad6775f49d6529e388fb01fd943898ec23 Mon Sep 17 00:00:00 2001 From: Olin Date: Thu, 19 May 2022 18:15:54 -0600 Subject: [PATCH 14/22] get routes configured properly --- src/app/app.go | 21 +++++++++++++-------- src/cmd/server.go | 22 +++++++++++++--------- src/rest/routes/device.go | 12 ++++++++---- src/rest/routes/routes.go | 21 ++++++++++++++++++--- 4 files changed, 52 insertions(+), 24 deletions(-) diff --git a/src/app/app.go b/src/app/app.go index 831b9672..a991cd35 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -1,22 +1,21 @@ package app import ( + "net/http" + "github.com/labstack/echo" log "github.com/sirupsen/logrus" "github.com/rna-vt/devicecommander/src/cluster" - "github.com/rna-vt/devicecommander/src/device" - "github.com/rna-vt/devicecommander/src/device/endpoint" "github.com/rna-vt/devicecommander/src/rest/routes" ) // The Application encapsulates the required state for the running software. type Application struct { - Cluster cluster.Cluster - Echo *echo.Echo - Hostname string - DeviceRepository device.Repository - EndpointRepository endpoint.Repository + Cluster cluster.Cluster + Echo *echo.Echo + Hostname string + Router routes.Router } // SystemInfo returns a stringified version of this api. @@ -30,7 +29,9 @@ func (a *Application) Start() { } func (a *Application) startListening() { - routes.BaseRouter{}.RegisterRoutes(a.Echo) + a.Echo.GET("/", hello) + + a.Router.RegisterRoutes(a.Echo) log.Info("Configured routes listening on " + a.Hostname) log.Println("*****************************************************") @@ -44,3 +45,7 @@ func (a *Application) startListening() { func (a *Application) startMaintainingCluster() { a.Cluster.Start() } + +func hello(c echo.Context) error { + return c.String(http.StatusOK, "Hello, World!") +} diff --git a/src/cmd/server.go b/src/cmd/server.go index f82ef054..d6a2094a 100644 --- a/src/cmd/server.go +++ b/src/cmd/server.go @@ -13,7 +13,8 @@ import ( "github.com/rna-vt/devicecommander/src/device" "github.com/rna-vt/devicecommander/src/postgres" postgresDevice "github.com/rna-vt/devicecommander/src/postgres/device" - postgresEndpoint "github.com/rna-vt/devicecommander/src/postgres/endpoint" + "github.com/rna-vt/devicecommander/src/rest/controllers" + "github.com/rna-vt/devicecommander/src/rest/routes" ) func init() { @@ -33,10 +34,14 @@ func NewServerCommand() *cobra.Command { return err } - endpointRepository, err := postgresEndpoint.NewRepository(dbConfig) - if err != nil { - log.Error(err) - return err + echoInstance := echo.New() + + router := routes.BaseRouter{ + DeviceRouter: routes.DeviceRouter{ + DeviceController: controllers.DeviceController{ + Repository: deviceRepository, + }, + }, } app := app.Application{ @@ -44,10 +49,9 @@ func NewServerCommand() *cobra.Command { viper.GetString("CLUSTER_NAME"), deviceRepository, device.NewHTTPDeviceClient(), ), - Echo: echo.New(), - Hostname: fmt.Sprintf("%s:%s", viper.GetString("HOST"), viper.GetString("PORT")), - DeviceRepository: deviceRepository, - EndpointRepository: endpointRepository, + Echo: echoInstance, + Hostname: fmt.Sprintf("%s:%s", viper.GetString("HOST"), viper.GetString("PORT")), + Router: router, } app.Start() diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index ff9f7003..291d5037 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -1,6 +1,8 @@ package routes import ( + "log" + "github.com/labstack/echo" "github.com/rna-vt/devicecommander/src/rest/controllers" @@ -11,7 +13,9 @@ type DeviceRouter struct { } func (r DeviceRouter) RegisterRoutes(e *echo.Echo) { - api := e.Group("/v1/device") + log.Println("register device routes") + api := e.Group("/v1") + api.POST("/", r.DeviceController.Create) // swagger:route GET /v1/device getAllDevices @@ -34,8 +38,8 @@ func (r DeviceRouter) RegisterRoutes(e *echo.Echo) { // default: genericError // 200: getAllDeviceResponse // 422: validationError - api.GET("/", r.DeviceController.GetAll) + api.GET("/device", r.DeviceController.GetAll) - api.GET("/:id", r.DeviceController.GetDevice) - api.DELETE("/:id", r.DeviceController.Delete) + api.GET("/device/:id", r.DeviceController.GetDevice) + api.DELETE("/device/:id", r.DeviceController.Delete) } diff --git a/src/rest/routes/routes.go b/src/rest/routes/routes.go index 456ae285..12fb2dfd 100644 --- a/src/rest/routes/routes.go +++ b/src/rest/routes/routes.go @@ -1,14 +1,20 @@ package routes import ( + "net/http" + "github.com/labstack/echo" "github.com/labstack/echo/middleware" "github.com/spf13/viper" ) -type Router interface{} +type Router interface { + RegisterRoutes(*echo.Echo) +} -type BaseRouter struct{} +type BaseRouter struct { + DeviceRouter +} func (r BaseRouter) RegisterRoutes(e *echo.Echo) { // Middleware @@ -21,6 +27,8 @@ func (r BaseRouter) RegisterRoutes(e *echo.Echo) { AllowOrigins: []string{"*"}, })) + e.GET("/base", hello) + r.registerFrontendRoutes(e) r.registerBackendRoutes(e) } @@ -37,5 +45,12 @@ func (r BaseRouter) registerFrontendRoutes(e *echo.Echo) { } func (r BaseRouter) registerBackendRoutes(e *echo.Echo) { - DeviceRouter{}.RegisterRoutes(e) + e.GET("/backend", hello) + api := e.Group("group") + api.GET("/base2", hello) + r.DeviceRouter.RegisterRoutes(e) +} + +func hello(c echo.Context) error { + return c.String(http.StatusOK, "Hello, World!") } From eec5770db3ecd09845bffabb4b753ce3030b5adc Mon Sep 17 00:00:00 2001 From: Olin Date: Thu, 19 May 2022 19:11:54 -0600 Subject: [PATCH 15/22] switch to echo v4 --- docs/docs.go | 35 +++++ docs/swagger.json | 211 +--------------------------- docs/swagger.yaml | 4 + go.mod | 15 +- go.sum | 88 ++++++++++++ src/app/app.go | 9 +- src/cmd/server.go | 2 +- src/rest/controllers/device.go | 2 +- src/rest/controllers/device_test.go | 2 +- src/rest/routes/device.go | 2 +- src/rest/routes/routes.go | 22 ++- 11 files changed, 166 insertions(+), 226 deletions(-) create mode 100644 docs/docs.go create mode 100644 docs/swagger.yaml diff --git a/docs/docs.go b/docs/docs.go new file mode 100644 index 00000000..e3e8dd03 --- /dev/null +++ b/docs/docs.go @@ -0,0 +1,35 @@ +// Package docs GENERATED BY SWAG; DO NOT EDIT +// This file was generated by swaggo/swag +package docs + +import "github.com/swaggo/swag" + +const docTemplate = `{ + "schemes": {{ marshal .Schemes }}, + "swagger": "2.0", + "info": { + "description": "{{escape .Description}}", + "title": "{{.Title}}", + "contact": {}, + "version": "{{.Version}}" + }, + "host": "{{.Host}}", + "basePath": "{{.BasePath}}", + "paths": {} +}` + +// SwaggerInfo holds exported Swagger Info so clients can modify it +var SwaggerInfo = &swag.Spec{ + Version: "", + Host: "", + BasePath: "", + Schemes: []string{}, + Title: "", + Description: "", + InfoInstanceName: "swagger", + SwaggerTemplate: docTemplate, +} + +func init() { + swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) +} diff --git a/docs/swagger.json b/docs/swagger.json index 64535881..ec416cd4 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1,210 +1,7 @@ { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http" - ], - "swagger": "2.0", - "info": { - "description": "DeviceCommander API documentation.", - "title": "DeviceCommander.", - "version": "1.0.0" - }, - "host": "device-commander.rna-vt.com", - "basePath": "/", - "paths": { - "/v1/device": { - "get": { - "description": "This will show all devices stored in the DB.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "summary": "Lists all Devices", - "operationId": "getAllDevices", - "responses": { - "200": { - "$ref": "#/responses/getAllDeviceResponse" - }, - "422": { - "$ref": "#/responses/validationError" - }, - "default": { - "$ref": "#/responses/genericError" - } - } - } - } - }, - "definitions": { - "Device": { - "description": "Device is one of the core concepts of this application. A Device represents\na microcontroller that complies with the DeviceCommander standard.", - "type": "object", - "required": [ - "ID", - "MAC", - "Host", - "Port" - ], - "properties": { - "Active": { - "description": "a flag representing the responsiveness of the device.", - "type": "boolean" - }, - "Description": { - "description": "the description of the device.", - "type": "string" - }, - "Endpoints": { - "description": "a list of endpoints available for quering on a device.", - "type": "array", - "items": { - "$ref": "#/definitions/Endpoint" - } - }, - "Failures": { - "description": "the count of failed actions by the device.", - "type": "integer", - "format": "int64" - }, - "Host": { - "description": "the host address of the device.", - "type": "string" - }, - "ID": { - "$ref": "#/definitions/UUID" - }, - "MAC": { - "description": "the MAC address for this device.", - "type": "string" - }, - "Name": { - "description": "the human readable name of the device.", - "type": "string" - }, - "Port": { - "description": "the active port of the device.", - "type": "integer", - "format": "int64" - } - }, - "x-go-package": "github.com/rna-vt/devicecommander/src/device" + "swagger": "2.0", + "info": { + "contact": {} }, - "Endpoint": { - "description": "Future possible example endpoints:\n\"on/off\"\n\"set artnet universe\"\n\"set color\"\n\"read temperature\"", - "type": "object", - "title": "An Endpoint is a single api endpoint served and described by the device.", - "properties": { - "Description": { - "type": "string" - }, - "DeviceID": { - "$ref": "#/definitions/UUID" - }, - "ID": { - "$ref": "#/definitions/UUID" - }, - "Method": { - "type": "string" - }, - "Parameters": { - "type": "array", - "items": { - "$ref": "#/definitions/Parameter" - } - }, - "Path": { - "type": "string" - }, - "Type": { - "type": "string" - } - }, - "x-go-package": "github.com/rna-vt/devicecommander/src/device/endpoint" - }, - "Parameter": { - "type": "object", - "title": "A Parameter is used in conjunction with an Endpoint to define a control point for a device.", - "properties": { - "Description": { - "type": "string" - }, - "EndpointID": { - "$ref": "#/definitions/UUID" - }, - "ID": { - "$ref": "#/definitions/UUID" - }, - "Name": { - "type": "string" - }, - "Type": { - "type": "string" - } - }, - "x-go-package": "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" - }, - "UUID": { - "description": "A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC\n4122.", - "type": "array", - "items": { - "type": "integer", - "format": "uint8" - }, - "x-go-package": "github.com/google/uuid" - } - }, - "responses": { - "getAllDeviceResponse": { - "description": "GetAllDeviceResponse is a response for the GetAllDevices endpoint.", - "schema": { - "type": "object", - "required": [ - "Devices", - "Message" - ], - "properties": { - "Message": { - "type": "string", - "example": "Expected type string" - } - } - } - }, - "validationError": { - "description": "A ValidationError is an error that is used when the required input fails validation.", - "schema": { - "type": "object", - "required": [ - "Message" - ], - "properties": { - "FieldName": { - "description": "An optional field name to which this validation applies", - "type": "string" - }, - "Message": { - "description": "The validation message", - "type": "string", - "example": "Expected type int" - } - } - } - } - }, - "securityDefinitions": { - "basic": { - "type": "basic" - } - } + "paths": {} } \ No newline at end of file diff --git a/docs/swagger.yaml b/docs/swagger.yaml new file mode 100644 index 00000000..b64379ca --- /dev/null +++ b/docs/swagger.yaml @@ -0,0 +1,4 @@ +info: + contact: {} +paths: {} +swagger: "2.0" diff --git a/go.mod b/go.mod index 73caabde..2e263842 100644 --- a/go.mod +++ b/go.mod @@ -3,14 +3,17 @@ module github.com/rna-vt/devicecommander go 1.15 require ( - github.com/99designs/gqlgen v0.16.0 + github.com/99designs/gqlgen v0.16.0 // indirect github.com/agnivade/levenshtein v1.1.1 // indirect github.com/bxcodec/faker/v3 v3.6.0 github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect + github.com/go-openapi/spec v0.20.6 // indirect + github.com/go-openapi/swag v0.21.1 // indirect github.com/google/gopacket v1.1.19 github.com/google/uuid v1.3.0 github.com/jackc/pgx/v4 v4.14.1 // indirect github.com/labstack/echo v3.3.10+incompatible + github.com/labstack/echo/v4 v4.7.2 github.com/labstack/gommon v0.3.1 github.com/lib/pq v1.10.3 // indirect github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect @@ -19,10 +22,12 @@ require ( github.com/spf13/cobra v1.3.0 github.com/spf13/viper v1.10.1 github.com/stretchr/testify v1.7.0 - github.com/vektah/gqlparser/v2 v2.3.1 - golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce // indirect - golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d // indirect - golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a // indirect + github.com/swaggo/echo-swagger v1.3.2 + github.com/swaggo/swag v1.8.2 + github.com/vektah/gqlparser/v2 v2.3.1 // indirect + golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898 // indirect + golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 // indirect + golang.org/x/sys v0.0.0-20220519141025-dcacdad47464 // indirect gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect gorm.io/driver/postgres v1.2.3 gorm.io/gorm v1.22.5 diff --git a/go.sum b/go.sum index f97faffc..e87c200b 100644 --- a/go.sum +++ b/go.sum @@ -54,9 +54,16 @@ github.com/99designs/gqlgen v0.16.0/go.mod h1:nbeSjFkqphIqpZsYe1ULVz0yfH8hjpJdJI github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc= github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM= github.com/agnivade/levenshtein v1.1.0/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8= @@ -109,8 +116,10 @@ github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7 github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -134,6 +143,7 @@ github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -144,12 +154,30 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= +github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= +github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= +github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= +github.com/go-openapi/spec v0.20.6 h1:ich1RQ3WDbfoeTqTAb+5EIxNmpKVJZWBNah9RAT0jIQ= +github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.21.1 h1:wm0rhTb5z7qpJRHBdPOMuY4QjVUMbF6/kwoYeRAOrKU= +github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw= github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -227,6 +255,7 @@ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5m github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= @@ -324,12 +353,15 @@ github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkr github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas= github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kevinmbeaulieu/eq-go v1.0.0/go.mod h1:G3S8ajA56gKBZm4UB9AOyoOS37JO3roToPzKNM8dtdM= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -344,8 +376,12 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= +github.com/labstack/echo/v4 v4.7.2 h1:Kv2/p8OaQ+M6Ex4eGimg9b9e6icoxA42JSlOR3msKtI= +github.com/labstack/echo/v4 v4.7.2/go.mod h1:xkCDAdFCIf8jsFQ5NnbK7oqaF/yU1A1X20Ltm0OvSks= github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o= github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -358,6 +394,12 @@ github.com/logrusorgru/aurora/v3 v3.0.0/go.mod h1:vsR12bk5grlLvLXAYrBsb5Oc/N+LxA github.com/lyft/protoc-gen-star v0.5.3/go.mod h1:V0xaHgaf5oCCqmcxYcWiDfTiKsZsRc87/1qhoTACD8w= github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/matryer/moq v0.2.3/go.mod h1:9RtPYjTnH1bSBIkpvtHkFN7nbWAnO7oRpdJkEIn6UtE= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= @@ -396,6 +438,11 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U= +github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= +github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= +github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= +github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.9.4 h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM= @@ -428,6 +475,7 @@ github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sagikazarmark/crypt v0.3.0/go.mod h1:uD/D+6UF4SrIR1uGEv7bBNkNqLGqUr43MRiaGWX1Nig= @@ -445,6 +493,8 @@ github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMB github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.3.3/go.mod h1:5KUK8ByomD5Ti5Artl0RtHeI5pTF7MIDuXL3yY520V4= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= @@ -474,7 +524,15 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/swaggo/echo-swagger v1.3.2 h1:D+3BNl8JMC6pKhA+egjh4LGI0jNesqlt77WahTHfTXQ= +github.com/swaggo/echo-swagger v1.3.2/go.mod h1:Sjj0O7Puf939HXhxhfZdR49MIrtcg3mLgdg3/qVcbyw= +github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 h1:+iNTcqQJy0OZ5jk6a5NLib47eqXK8uYcPX+O4+cBpEM= +github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w= +github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ= +github.com/swaggo/swag v1.8.2 h1:D4aBiVS2a65zhyk3WFqOUz7Rz0sOaUcgeErcid5uGL4= +github.com/swaggo/swag v1.8.2/go.mod h1:jMLeXOOmYyjk8PvHTsXBdrubsNd9gUJTTCzL5iBnseg= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= +github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= @@ -488,6 +546,8 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= go.etcd.io/etcd/api/v3 v3.5.1/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.1/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= @@ -533,6 +593,10 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce h1:Roh6XWxHFKrPgC/EQhVubSAGQ6Ozk6IdxHSzt1mR0EI= golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA= +golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898 h1:SLP7Q4Di66FONjDJbCYrCRrh97focO6sLogHO7/g8F0= +golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -569,6 +633,7 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -610,11 +675,18 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d h1:1n1fc535VhN8SYtD4cDUyNlfpAF2ROMM9+11equK3hs= golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 h1:NWy5+hlRbC7HK+PmcXVUmW1IMyFce7to56IUvhUFm7Y= +golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -696,6 +768,7 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -705,19 +778,27 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a h1:ppl5mZgokTT8uPkmYOyEUmPTr3ypaKkg5eFOGrAmxxE= golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 h1:xHms4gcpe1YE7A3yIllJXP16CMAGuqwO2lX1mTyyRRc= +golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220519141025-dcacdad47464 h1:MpIuURY70f0iKp/oooEFtB2oENcHITo/z1b6u41pKCw= +golang.org/x/sys v0.0.0-20220519141025-dcacdad47464/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -731,6 +812,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 h1:Hir2P/De0WpUhtrKGGjvSb2YxUgyZ7EFOSLIcSSpiwE= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -738,6 +821,7 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3 golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -793,6 +877,9 @@ golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -965,6 +1052,7 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gorm.io/driver/postgres v1.2.3 h1:f4t0TmNMy9gh3TU2PX+EppoA6YsgFnyq8Ojtddb42To= diff --git a/src/app/app.go b/src/app/app.go index a991cd35..79ccf75a 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -1,9 +1,7 @@ package app import ( - "net/http" - - "github.com/labstack/echo" + "github.com/labstack/echo/v4" log "github.com/sirupsen/logrus" "github.com/rna-vt/devicecommander/src/cluster" @@ -29,7 +27,6 @@ func (a *Application) Start() { } func (a *Application) startListening() { - a.Echo.GET("/", hello) a.Router.RegisterRoutes(a.Echo) log.Info("Configured routes listening on " + a.Hostname) @@ -45,7 +42,3 @@ func (a *Application) startListening() { func (a *Application) startMaintainingCluster() { a.Cluster.Start() } - -func hello(c echo.Context) error { - return c.String(http.StatusOK, "Hello, World!") -} diff --git a/src/cmd/server.go b/src/cmd/server.go index d6a2094a..b3329be1 100644 --- a/src/cmd/server.go +++ b/src/cmd/server.go @@ -3,7 +3,7 @@ package cmd import ( "fmt" - "github.com/labstack/echo" + "github.com/labstack/echo/v4" "github.com/labstack/gommon/log" "github.com/spf13/cobra" "github.com/spf13/viper" diff --git a/src/rest/controllers/device.go b/src/rest/controllers/device.go index 81e51f08..f9f10388 100644 --- a/src/rest/controllers/device.go +++ b/src/rest/controllers/device.go @@ -4,7 +4,7 @@ import ( "net/http" "github.com/google/uuid" - "github.com/labstack/echo" + "github.com/labstack/echo/v4" log "github.com/sirupsen/logrus" "github.com/rna-vt/devicecommander/src/device" diff --git a/src/rest/controllers/device_test.go b/src/rest/controllers/device_test.go index 3d513066..7c74f1a5 100644 --- a/src/rest/controllers/device_test.go +++ b/src/rest/controllers/device_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/google/uuid" - "github.com/labstack/echo" + "github.com/labstack/echo/v4" "github.com/stretchr/testify/suite" mocks "github.com/rna-vt/devicecommander/mocks/device" diff --git a/src/rest/routes/device.go b/src/rest/routes/device.go index 291d5037..587e1547 100644 --- a/src/rest/routes/device.go +++ b/src/rest/routes/device.go @@ -3,7 +3,7 @@ package routes import ( "log" - "github.com/labstack/echo" + "github.com/labstack/echo/v4" "github.com/rna-vt/devicecommander/src/rest/controllers" ) diff --git a/src/rest/routes/routes.go b/src/rest/routes/routes.go index 12fb2dfd..d66660d4 100644 --- a/src/rest/routes/routes.go +++ b/src/rest/routes/routes.go @@ -3,15 +3,32 @@ package routes import ( "net/http" - "github.com/labstack/echo" - "github.com/labstack/echo/middleware" + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" "github.com/spf13/viper" + echoSwagger "github.com/swaggo/echo-swagger" + + _ "github.com/swaggo/echo-swagger/example/docs" ) type Router interface { RegisterRoutes(*echo.Echo) } +// @title Swagger Example API +// @version 1.0 +// @description This is a sample server Petstore server. +// @termsOfService http://swagger.io/terms/ + +// @contact.name API Support +// @contact.url http://www.swagger.io/support +// @contact.email support@swagger.io + +// @license.name Apache 2.0 +// @license.url http://www.apache.org/licenses/LICENSE-2.0.html + +// @host petstore.swagger.io +// @BasePath /v2 type BaseRouter struct { DeviceRouter } @@ -27,6 +44,7 @@ func (r BaseRouter) RegisterRoutes(e *echo.Echo) { AllowOrigins: []string{"*"}, })) + e.GET("/swagger/*", echoSwagger.WrapHandler) e.GET("/base", hello) r.registerFrontendRoutes(e) From eee4450db5f5a37102f00f5bccd0a32b9df677f1 Mon Sep 17 00:00:00 2001 From: Olin Date: Fri, 3 Jun 2022 15:47:22 -0600 Subject: [PATCH 16/22] lint fix --- src/app/app.go | 1 - src/rest/routes/routes.go | 4 +--- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/app/app.go b/src/app/app.go index 79ccf75a..1d4d032e 100644 --- a/src/app/app.go +++ b/src/app/app.go @@ -27,7 +27,6 @@ func (a *Application) Start() { } func (a *Application) startListening() { - a.Router.RegisterRoutes(a.Echo) log.Info("Configured routes listening on " + a.Hostname) diff --git a/src/rest/routes/routes.go b/src/rest/routes/routes.go index d66660d4..18e36e6d 100644 --- a/src/rest/routes/routes.go +++ b/src/rest/routes/routes.go @@ -7,8 +7,6 @@ import ( "github.com/labstack/echo/v4/middleware" "github.com/spf13/viper" echoSwagger "github.com/swaggo/echo-swagger" - - _ "github.com/swaggo/echo-swagger/example/docs" ) type Router interface { @@ -28,7 +26,7 @@ type Router interface { // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host petstore.swagger.io -// @BasePath /v2 +// @BasePath /v2. type BaseRouter struct { DeviceRouter } From 2b45569679e25fcb2eb3639fe583869abc651e12 Mon Sep 17 00:00:00 2001 From: Olin Date: Mon, 20 Jun 2022 13:42:07 -0600 Subject: [PATCH 17/22] swag --- docs/index.html | 4 +- docs/swagger.json | 211 ++++++++++++++++++++++++++++++++++++++++- src/cluster/cluster.go | 2 - 3 files changed, 209 insertions(+), 8 deletions(-) diff --git a/docs/index.html b/docs/index.html index 2095f5b1..1518d758 100644 --- a/docs/index.html +++ b/docs/index.html @@ -6,6 +6,6 @@ Device Commander Docs - + - \ No newline at end of file + diff --git a/docs/swagger.json b/docs/swagger.json index ec416cd4..64535881 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1,7 +1,210 @@ { - "swagger": "2.0", - "info": { - "contact": {} + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http" + ], + "swagger": "2.0", + "info": { + "description": "DeviceCommander API documentation.", + "title": "DeviceCommander.", + "version": "1.0.0" + }, + "host": "device-commander.rna-vt.com", + "basePath": "/", + "paths": { + "/v1/device": { + "get": { + "description": "This will show all devices stored in the DB.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http", + "https" + ], + "summary": "Lists all Devices", + "operationId": "getAllDevices", + "responses": { + "200": { + "$ref": "#/responses/getAllDeviceResponse" + }, + "422": { + "$ref": "#/responses/validationError" + }, + "default": { + "$ref": "#/responses/genericError" + } + } + } + } + }, + "definitions": { + "Device": { + "description": "Device is one of the core concepts of this application. A Device represents\na microcontroller that complies with the DeviceCommander standard.", + "type": "object", + "required": [ + "ID", + "MAC", + "Host", + "Port" + ], + "properties": { + "Active": { + "description": "a flag representing the responsiveness of the device.", + "type": "boolean" + }, + "Description": { + "description": "the description of the device.", + "type": "string" + }, + "Endpoints": { + "description": "a list of endpoints available for quering on a device.", + "type": "array", + "items": { + "$ref": "#/definitions/Endpoint" + } + }, + "Failures": { + "description": "the count of failed actions by the device.", + "type": "integer", + "format": "int64" + }, + "Host": { + "description": "the host address of the device.", + "type": "string" + }, + "ID": { + "$ref": "#/definitions/UUID" + }, + "MAC": { + "description": "the MAC address for this device.", + "type": "string" + }, + "Name": { + "description": "the human readable name of the device.", + "type": "string" + }, + "Port": { + "description": "the active port of the device.", + "type": "integer", + "format": "int64" + } + }, + "x-go-package": "github.com/rna-vt/devicecommander/src/device" }, - "paths": {} + "Endpoint": { + "description": "Future possible example endpoints:\n\"on/off\"\n\"set artnet universe\"\n\"set color\"\n\"read temperature\"", + "type": "object", + "title": "An Endpoint is a single api endpoint served and described by the device.", + "properties": { + "Description": { + "type": "string" + }, + "DeviceID": { + "$ref": "#/definitions/UUID" + }, + "ID": { + "$ref": "#/definitions/UUID" + }, + "Method": { + "type": "string" + }, + "Parameters": { + "type": "array", + "items": { + "$ref": "#/definitions/Parameter" + } + }, + "Path": { + "type": "string" + }, + "Type": { + "type": "string" + } + }, + "x-go-package": "github.com/rna-vt/devicecommander/src/device/endpoint" + }, + "Parameter": { + "type": "object", + "title": "A Parameter is used in conjunction with an Endpoint to define a control point for a device.", + "properties": { + "Description": { + "type": "string" + }, + "EndpointID": { + "$ref": "#/definitions/UUID" + }, + "ID": { + "$ref": "#/definitions/UUID" + }, + "Name": { + "type": "string" + }, + "Type": { + "type": "string" + } + }, + "x-go-package": "github.com/rna-vt/devicecommander/src/device/endpoint/parameter" + }, + "UUID": { + "description": "A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC\n4122.", + "type": "array", + "items": { + "type": "integer", + "format": "uint8" + }, + "x-go-package": "github.com/google/uuid" + } + }, + "responses": { + "getAllDeviceResponse": { + "description": "GetAllDeviceResponse is a response for the GetAllDevices endpoint.", + "schema": { + "type": "object", + "required": [ + "Devices", + "Message" + ], + "properties": { + "Message": { + "type": "string", + "example": "Expected type string" + } + } + } + }, + "validationError": { + "description": "A ValidationError is an error that is used when the required input fails validation.", + "schema": { + "type": "object", + "required": [ + "Message" + ], + "properties": { + "FieldName": { + "description": "An optional field name to which this validation applies", + "type": "string" + }, + "Message": { + "description": "The validation message", + "type": "string", + "example": "Expected type int" + } + } + } + } + }, + "securityDefinitions": { + "basic": { + "type": "basic" + } + } } \ No newline at end of file diff --git a/src/cluster/cluster.go b/src/cluster/cluster.go index 86bf6e0a..bd51a5c2 100644 --- a/src/cluster/cluster.go +++ b/src/cluster/cluster.go @@ -123,8 +123,6 @@ func (c DeviceCluster) RunHealthCheckLoop(healthCheckPeriod int) { } for _, dev := range devices { - // dev := device.NewDeviceWrapper(*d) - resp, err := c.DeviceClient.Health(*dev) if err != nil { c.logger.Warn(fmt.Sprintf("error checking health for device [%s] %s", dev.ID.String(), err)) From 34bfdd3f982a5f96f18c937ee724919397488829 Mon Sep 17 00:00:00 2001 From: Olin Date: Mon, 20 Jun 2022 14:04:02 -0600 Subject: [PATCH 18/22] try next gen image --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index c112a579..43aa414c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,7 +4,7 @@ parameters: type: string default: "0.0.1" orbs: - docker: circleci/docker@1.7.0 + docker: cimg/base:2022.06 executors: docker-publisher: docker: From f21f44bb1f4d95da61065c17b5af85d45f56ff95 Mon Sep 17 00:00:00 2001 From: Olin Date: Mon, 20 Jun 2022 14:04:53 -0600 Subject: [PATCH 19/22] try next gen image --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 43aa414c..5906ccdf 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,11 +4,11 @@ parameters: type: string default: "0.0.1" orbs: - docker: cimg/base:2022.06 + docker: circleci/docker@1.7.0 executors: docker-publisher: docker: - - image: circleci/buildpack-deps:latest-alpine + - image: cimg/base:2022.06 jobs: test: docker: From 76260f02378687f4c7b73325fb636a9c1a77bafb Mon Sep 17 00:00:00 2001 From: Olin Date: Mon, 20 Jun 2022 14:06:18 -0600 Subject: [PATCH 20/22] build and publish trigger --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 5906ccdf..2b5ab608 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -105,4 +105,4 @@ workflows: filters: branches: only: - - master + # - master From 71dea7bbde9c8132854374237fa908fea2d524db Mon Sep 17 00:00:00 2001 From: Olin Date: Mon, 20 Jun 2022 14:11:13 -0600 Subject: [PATCH 21/22] try bumping docker orb --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2b5ab608..b9cd9c9c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,7 +4,7 @@ parameters: type: string default: "0.0.1" orbs: - docker: circleci/docker@1.7.0 + docker: circleci/docker@2.1.2 executors: docker-publisher: docker: From 3cb0959515b4ed95f3e1ed5352e34dd0e6c58ffe Mon Sep 17 00:00:00 2001 From: Olin Date: Mon, 20 Jun 2022 14:15:09 -0600 Subject: [PATCH 22/22] use next gen --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b9cd9c9c..c5509c39 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -12,7 +12,7 @@ executors: jobs: test: docker: - - image: circleci/golang:1.16 + - image: cimg/go:1.16 auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD @@ -62,7 +62,7 @@ jobs: build: docker: - - image: circleci/golang:1.16 + - image: cimg/go:1.16 auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD