package api import ( "3dshow/db/model" "3dshow/db/repo" "errors" "time" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/bson/primitive" ) func Address(r *GinRouter) { CreateCRUD(r, "/address", &CRUDOption{ Collection: repo.CollectionAddress, NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) { entity := &model.Address{} c.ShouldBindJSON(entity) entity.CreateTime = time.Now() _userId := apictx.User.ID userId, err := primitive.ObjectIDFromHex(_userId) if err != nil { return nil, errors.New("非法用户") } if entity.Addr == "" { return nil, errors.New("地址不能为空") } if entity.Contact == "" { return nil, errors.New("联系人不能为空") } entity.UserId = userId // 默认设置第一条数据为默认数据 first, _ := repo.RepoCountDoc(apictx.CreateRepoCtx(), repo.CollectionAddress, repo.Map{"userId": userId}) if first > 0 { entity.Defualt = -1 } else { entity.Defualt = 1 } return entity, nil }, OnUpdate: func(_ *gin.Context, apictx *ApiSession, entity interface{}) { address := entity.(*model.Address) _userId := apictx.User.ID userId, err := primitive.ObjectIDFromHex(_userId) if err != nil { invalidId, _ := primitive.ObjectIDFromHex("6369f4b028c4bf8b14f47a6b") userId = invalidId } // 更改默认地址的流程 if address.Defualt == 1 { // 将已有的默认地址更改为非默认 opt := repo.PageSearchOptions{ CollectName: repo.CollectionAddress, Query: repo.Map{"userId": userId, "defualt": 1}, Project: []string{"_id"}, } defs := make([]*model.Address, 0) repo.RepoDocsSearch(apictx.CreateRepoCtx(), &opt, &defs) if len(defs) > 0 { for _, v := range defs { // 设置为非默认 repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionAddress, v.Id.Hex(), &model.Address{Defualt: -1}) } } } }, EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} { return &model.Address{} }, JWT: true, SearchFilter: func(_ *gin.Context, apictx *ApiSession, query map[string]interface{}) map[string]interface{} { _userId := apictx.User.ID userId, err := primitive.ObjectIDFromHex(_userId) if err != nil { // 6369f4b028c4bf8b14f47a6b invalidId, _ := primitive.ObjectIDFromHex("6369f4b028c4bf8b14f47a6b") query["userId"] = invalidId return query } query["userId"] = userId return query }, SearchProject: []string{"province", "city", "area", "addr", "contact", "phone", "defualt", "createTime"}, DetailProject: []string{"province", "city", "area", "addr", "contact", "phone", "defualt", "createTime"}, }) }