github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/domain/formation/converter.go (about) 1 package formation 2 3 import ( 4 "encoding/json" 5 6 "github.com/kyma-incubator/compass/components/director/internal/model" 7 "github.com/kyma-incubator/compass/components/director/internal/repo" 8 "github.com/kyma-incubator/compass/components/director/pkg/graphql" 9 "github.com/pkg/errors" 10 ) 11 12 type converter struct { 13 } 14 15 // NewConverter creates new formation converter 16 func NewConverter() *converter { 17 return &converter{} 18 } 19 20 // FromGraphQL converts graphql.FormationInput to model.Formation 21 func (c *converter) FromGraphQL(i graphql.FormationInput) model.Formation { 22 f := model.Formation{ 23 Name: i.Name, 24 } 25 if i.State != nil { 26 f.State = model.FormationState(*i.State) 27 } 28 return f 29 } 30 31 // ToGraphQL converts model.Formation to graphql.Formation 32 func (c *converter) ToGraphQL(i *model.Formation) (*graphql.Formation, error) { 33 if i == nil { 34 return nil, nil 35 } 36 37 var formationErr graphql.FormationError 38 if i.Error != nil { 39 if err := json.Unmarshal(i.Error, &formationErr); err != nil { 40 return nil, errors.Wrapf(err, "while unmarshalling formation error with ID %q", i.ID) 41 } 42 } 43 44 return &graphql.Formation{ 45 ID: i.ID, 46 Name: i.Name, 47 FormationTemplateID: i.FormationTemplateID, 48 State: string(i.State), 49 Error: formationErr, 50 }, nil 51 } 52 53 // MultipleToGraphQL converts multiple internal models to GraphQL models 54 func (c *converter) MultipleToGraphQL(in []*model.Formation) ([]*graphql.Formation, error) { 55 if in == nil { 56 return nil, nil 57 } 58 formations := make([]*graphql.Formation, 0, len(in)) 59 for _, f := range in { 60 if f == nil { 61 continue 62 } 63 64 formation, err := c.ToGraphQL(f) 65 if err != nil { 66 return nil, err 67 } 68 formations = append(formations, formation) 69 } 70 71 return formations, nil 72 } 73 74 func (c *converter) ToEntity(in *model.Formation) *Entity { 75 if in == nil { 76 return nil 77 } 78 79 return &Entity{ 80 ID: in.ID, 81 TenantID: in.TenantID, 82 FormationTemplateID: in.FormationTemplateID, 83 Name: in.Name, 84 State: string(in.State), 85 Error: repo.NewNullableStringFromJSONRawMessage(in.Error), 86 } 87 } 88 89 func (c *converter) FromEntity(entity *Entity) *model.Formation { 90 if entity == nil { 91 return nil 92 } 93 94 return &model.Formation{ 95 ID: entity.ID, 96 TenantID: entity.TenantID, 97 FormationTemplateID: entity.FormationTemplateID, 98 Name: entity.Name, 99 State: model.FormationState(entity.State), 100 Error: repo.JSONRawMessageFromNullableString(entity.Error), 101 } 102 }