-
Notifications
You must be signed in to change notification settings - Fork 0
/
maelstromMongo.go
108 lines (90 loc) · 2.16 KB
/
maelstromMongo.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"google.golang.org/cloud/compute/metadata"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var mongoUrl string = "localhost:27017"
var dbName string = "test"
type MongoDatastore struct{}
func (db *MongoDatastore) Ping() bool {
if gce {
mongoUrl, _ = metadata.InstanceAttributeValue("mongoUrl")
if Debug {
InfoLog.Println("Mongo URL pulled from GCE Metadata: " + mongoUrl)
}
}
session, err := mgo.Dial(mongoUrl)
if err != nil {
return false
}
session.Close()
return true
}
func (db *MongoDatastore) StoreContact(contact Contact) Contact {
session, err := mgo.Dial(mongoUrl)
check(err)
defer session.Close()
contact.Id = bson.NewObjectId()
c := session.DB(dbName).C("contact")
err = c.Insert(&contact)
if err != nil {
ErrorLog.Println("Error storing Contact: " + contact.Name)
return Contact{}
}
return contact
}
func (db *MongoDatastore) UpdateContact(contact Contact) Contact {
session, err := mgo.Dial(mongoUrl)
check(err)
defer session.Close()
c := session.DB(dbName).C("contact")
err = c.UpdateId(contact.Id, &contact)
if err != nil {
return Contact{}
}
return contact
}
func (db *MongoDatastore) RetrieveContactsBy(param string, value string) []Contact {
session, err := mgo.Dial(mongoUrl)
check(err)
defer session.Close()
c := session.DB(dbName).C("contact")
result := []Contact{}
if param == "id" {
contact := Contact{}
oid := bson.ObjectIdHex(value)
err = c.FindId(oid).One(&contact)
if err != nil {
if Debug {
InfoLog.Printf("Cannot retrieve contact where %s = %s \n", param, value)
}
}
result = make([]Contact, 1, 1)
result[0] = contact
} else {
err = c.Find(bson.M{param: value}).All(&result)
if err != nil {
if Debug {
InfoLog.Printf("Cannot retrieve contact where %s = %s \n", param, value)
}
return []Contact{}
}
}
return result
}
func (db *MongoDatastore) DeleteContact(id string) bool {
session, err := mgo.Dial(mongoUrl)
check(err)
defer session.Close()
objectId := bson.ObjectIdHex(id)
c := session.DB(dbName).C("contact")
err = c.RemoveId(objectId)
if err != nil {
return false
}
return true
}
func (db *MongoDatastore) Status() bool {
return true
}