/
dealers.go
127 lines (105 loc) · 2.95 KB
/
dealers.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package database
import (
"context"
"log"
"time"
"github.com/bujosa/xihe/utils"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Dealer struct {
Id string `bson:"_id"`
Name string `bson:"name"`
Slug string `bson:"slug"`
Address string `bson:"address"`
Latitude float64 `bson:"latitude"`
Longitude float64 `bson:"longitude"`
TelephoneNumberSanitized string `bson:"telephoneNumberSanitized"`
City string `bson:"city"`
Spot string `bson:"spot"`
Uploaded bool `bson:"uploaded"`
Dealer string `bson:"dealer"`
}
type UpdateDealerInfo struct {
Id string `bson:"_id"`
Set bson.M `bson:"$set"`
}
func GetDealers(ctx context.Context) []Dealer {
dbUri := ctx.Value(utils.DbUri).(string)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(
dbUri,
))
if err != nil {
log.Println("Error connecting to database: " + dbUri)
return nil
}
db := client.Database(utils.DATABASE)
coll := db.Collection(utils.DEALERS_COLLECTION)
pipeline := []bson.M{
{
"$match": bson.M{
"uploaded": false,
},
},
{
"$project": bson.M{
"dealer": 1,
"uploaded": 1,
"name": 1,
"slug": 1,
"address": 1,
"latitude": 1,
"longitude": 1,
"telephoneNumberSanitized": 1,
"city": 1,
"spot": 1,
},
},
}
cursor, err := coll.Aggregate(ctx, pipeline)
if err != nil {
log.Println("Error getting dealers")
panic(err)
}
dealers := []Dealer{}
for cursor.Next(ctx) {
var doc Dealer
err := cursor.Decode(&doc)
if err != nil {
log.Println("Error decoding dealer with error " + err.Error())
panic(err)
}
dealers = append(dealers, doc)
}
return dealers
}
func UpdateDealer(ctx context.Context, updateDealerInfo UpdateDealerInfo) {
log.Println("Updating dealer: " + updateDealerInfo.Id)
dbUri := ctx.Value(utils.DbUri).(string)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(
dbUri,
))
if err != nil {
log.Println("Error connecting to database: " + dbUri)
return
}
db := client.Database(utils.DATABASE)
coll := db.Collection(utils.DEALERS_COLLECTION)
objectId, err := utils.ToObjectId(updateDealerInfo.Id)
if err != nil {
log.Println("Error converting id to ObjectId: " + updateDealerInfo.Id)
return
}
filter := bson.M{"_id": objectId}
update := bson.M{
"$set": updateDealerInfo.Set,
}
update["$set"].(bson.M)["updatedAt"] = time.Now().UTC()
_, err = coll.UpdateOne(context.Background(), filter, update)
if err != nil {
log.Print("Error updating dealer: " + updateDealerInfo.Id)
return
}
log.Println("Updated dealer: " + updateDealerInfo.Id)
}