From b938f505cf77e2778e63a0caa8ac7e64c71979d2 Mon Sep 17 00:00:00 2001 From: Sinh Date: Wed, 6 Jul 2022 09:07:56 +0700 Subject: [PATCH] add filter author and time --- action_query.go | 46 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/action_query.go b/action_query.go index 903c2a9..7a86196 100644 --- a/action_query.go +++ b/action_query.go @@ -3,6 +3,7 @@ package audit import ( "context" "sync" + "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/options" @@ -12,9 +13,16 @@ import ( type AllQuery struct { Target string TargetID string - Page int64 - Limit int64 - Sort interface{} + + // Additional filter + Author string + CreateTimeFrom time.Time + CreateTimeTo time.Time + + // Pagination + Page int64 + Limit int64 + Sort interface{} } // All ... @@ -25,10 +33,7 @@ func (s Service) All(query AllQuery) (result []Audit, total int64) { skip = query.Page * query.Limit wg sync.WaitGroup ) - cond := bson.D{ - {"target", query.Target}, - {"targetId", query.TargetID}, - } + cond := s.getQueryCondition(query) wg.Add(1) go func() { defer wg.Done() @@ -54,3 +59,30 @@ func (s Service) All(query AllQuery) (result []Audit, total int64) { wg.Wait() return result, total } + +func (s Service) getQueryCondition(query AllQuery) bson.D { + cond := bson.D{ + {"target", query.Target}, + {"targetId", query.TargetID}, + } + if query.Author != "" { + cond = append(cond, bson.E{ + Key: "author.id", + Value: query.Author, + }) + } + if !query.CreateTimeFrom.IsZero() || !query.CreateTimeTo.IsZero() { + v := bson.M{} + if !query.CreateTimeFrom.IsZero() { + v["$gte"] = query.CreateTimeFrom + } + if !query.CreateTimeTo.IsZero() { + v["$lt"] = query.CreateTimeTo + } + cond = append(cond, bson.E{ + Key: "createdAt", + Value: v, + }) + } + return cond +}