package accessmod import ( "context" "fmt" "stat/common/log" "stat/common/mongos" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // 初始化model func Init() { // 获取数据库表 db = mongos.New(mongos.MgoManager, CollAccessLog) // 初始化索引 indexes := []mongo.IndexModel{ { Keys: bson.D{{Key: "userId", Value: 1}, {Key: "appId", Value: 1}}, }, { Keys: bson.D{{Key: "appId", Value: 1}, {Key: "visitAt", Value: 1}}, }, { Keys: bson.D{{Key: "appId", Value: 1}, {Key: "userId", Value: 1}, {Key: "visitAt", Value: 1}}, Options: options.Index().SetUnique(true), }, { Keys: bson.D{{Key: "appId", Value: 1}, {Key: "userId", Value: 1}, {Key: "visitAt", Value: 1}, {Key: "registerTime", Value: 1}}, }, { Keys: bson.D{{Key: "createdAt", Value: 1}}, Options: options.Index().SetExpireAfterSeconds(5 * 24 * 60 * 60), }, { Keys: bson.D{{Key: "appId", Value: 1}, {Key: "userId", Value: 1}, {Key: "visitAt", Value: 1}, {Key: "isDirect", Value: 1}, {Key: "blocDeduction", Value: 1}}, }, } if _, err := db.CreateIndex(context.Background(), indexes); err != nil { panic(fmt.Sprintf("%s model set index err ==>[%+v]", CollAccessLog, err)) } } // 新增用户访问记录 func AddAccessLog(ctx context.Context, doc *AccessMod) (err error) { doc.CreatedAt = time.Now() if _, err = db.UpsertOne(ctx, bson.M{"visitAt": doc.VisitAt, "userId": doc.UserId, "appId": doc.AppId}, bson.M{"$setOnInsert": doc}); err != nil { log.Error("admin AddAccessLog InsertOne err", log.E(err)) return } return }