/
event.go
75 lines (63 loc) · 1.81 KB
/
event.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package mongo
import (
"github.com/AdhityaRamadhanus/gopatrol"
"github.com/AdhityaRamadhanus/gopatrol/config"
"gopkg.in/mgo.v2"
)
type EventService struct {
session *mgo.Session
CollName string
}
func NewEventService(session *mgo.Session, collName string) *EventService {
EventColl := session.DB(config.DatabaseName).C(collName)
EventColl.Create(&mgo.CollectionInfo{
Capped: true,
// Set Max Size in bytes to 5 GB (just a guess number)
MaxBytes: 5000 * 1000,
MaxDocs: 100000,
})
// Ensure Index
EventColl.EnsureIndex(mgo.Index{
Key: []string{"slug"},
Unique: false,
DropDups: false,
Background: true,
Sparse: true,
})
return &EventService{
session: session,
CollName: collName,
}
}
// for more flexible use
func (p *EventService) CopySession() *mgo.Session {
return p.session.Copy()
}
func (p *EventService) InsertEvent(event gopatrol.Event) error {
copySession := p.session.Copy()
defer copySession.Close()
EventColl := copySession.DB(config.DatabaseName).C(p.CollName)
return EventColl.Insert(event)
}
func (p *EventService) GetAllEvents(q map[string]interface{}) ([]gopatrol.Event, error) {
copySession := p.session.Copy()
defer copySession.Close()
EventColl := copySession.DB(config.DatabaseName).C(p.CollName)
events := []gopatrol.Event{}
MongoQuery := EventColl.Find(q["query"])
if ok, val := q["pagination"].(bool); ok && val {
MongoQuery.
Skip(q["page"].(int) * q["limit"].(int)).
Limit(q["limit"].(int))
}
if err := MongoQuery.Sort("-timestamp").All(&events); err != nil {
return nil, err
}
return events, nil
}
func (p *EventService) CountEvents(query map[string]interface{}) (int, error) {
copySession := p.session.Copy()
defer copySession.Close()
EventColl := copySession.DB(config.DatabaseName).C(p.CollName)
return EventColl.Find(query).Count()
}