package controller import ( "fmt" "git.cestong.com.cn/cecf/cecf-golib/pkg/apollo" "git.cestong.com.cn/cecf/cecf-golib/pkg/errors" gin2 "git.cestong.com.cn/cecf/cecf-golib/pkg/gin" "git.cestong.com.cn/cecf/config-center-server/pkg/model" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" "gorm.io/gorm" ) type ConfigFileController struct { db *gorm.DB val *validator.Validate apolloCli *apollo.HTTPClient } func NewConfigFileController(db *gorm.DB, val *validator.Validate, apolloCli *apollo.HTTPClient) *ConfigFileController { return &ConfigFileController{db: db, val: val, apolloCli: apolloCli} } type ConfigFileReqVO struct { Name string `json:"name" validate:"min=1"` Desc string `json:"desc"` Format string `json:"format" validate:"oneof=ini"` DefaultPath string `json:"defaultPath" validate:"min=1"` } func (cf *ConfigFileController) Create(c *gin.Context) (interface{}, error) { // req appIDStr := c.Param("appID") var req ConfigFileReqVO if errBind := c.ShouldBindJSON(&req); errBind != nil { return nil, errors.ErrBadRequest } if errVal := cf.val.Struct(&req); errVal != nil { return nil, errors.ErrBadRequest } // apollo req build apolloID := appIDStr apolloNamespace := fmt.Sprintf("%s.%s", req.Name, "properties") // filters { var sameNameCount int64 if errCount := cf.db.Model(&model.ConfigFileModel{}). Where("apollo_app_id=? and apollo_namespace=?", apolloID, apolloNamespace). Count(&sameNameCount).Error; errCount != nil { return nil, errCount } if sameNameCount > 0 { return nil, errors.Wrap(errors.ErrBadRequest, "名称(%s)重复", req.Name) } } // get app model from db var appModel model.AppModel { if errGetAppModel := cf.db.First(&appModel, "apollo_app_id=?", appIDStr).Error; errGetAppModel != nil { if errGetAppModel == gorm.ErrRecordNotFound { return nil, errors.Wrap(errors.ErrBadRequest, "appID(%s)未找到") } return nil, errGetAppModel } } // apollo create if errCreateApollo := cf.apolloCli.CreateNameSpace(apolloID, req.Name); errCreateApollo != nil { return nil, errCreateApollo } var m model.ConfigFileModel m.AppModelID = appModel.ID m.ApolloAppID = appIDStr m.Name = req.Name m.Format = req.Format m.Desc = req.Desc m.ApolloNamespace = apolloNamespace m.DefaultPath = req.DefaultPath // save to db if errCreate := cf.db.Create(&m).Error; errCreate != nil { return nil, errCreate } // resp return gin2.SuccessGeneralVO(), nil }