Mercurial > code > home > repos > gcalendarwatch
comparison calsync/mongoclient/cals_collection.go @ 50:dade5bbd02e3
refactor
author | drewp@bigasterisk.com |
---|---|
date | Mon, 19 Aug 2024 13:37:05 -0700 |
parents | |
children | a9b720445bcf |
comparison
equal
deleted
inserted
replaced
49:2991c1166852 | 50:dade5bbd02e3 |
---|---|
1 package mongoclient | |
2 | |
3 import ( | |
4 "log" | |
5 | |
6 "go.mongodb.org/mongo-driver/bson" | |
7 "go.mongodb.org/mongo-driver/mongo/options" | |
8 ) | |
9 | |
10 // docs in calsCollection | |
11 type MongoCal struct { | |
12 Url string `bson:"_id"` // bigasterisk.com/... | |
13 GoogleId string `bson:"googleId"` | |
14 Summary string `bson:"summary"` | |
15 Description string `bson:"description"` | |
16 } | |
17 | |
18 func (c *MongoClient) GetAllCals() ([]MongoCal, error) { | |
19 cur, err := c.calsCollection.Find(c.ctx, bson.D{}) | |
20 if err != nil { | |
21 return nil, err | |
22 } | |
23 defer cur.Close(c.ctx) | |
24 | |
25 var cals []MongoCal | |
26 for cur.Next(c.ctx) { | |
27 var cal MongoCal | |
28 if err := cur.Decode(&cal); err != nil { | |
29 return nil, err | |
30 } | |
31 cals = append(cals, cal) | |
32 } | |
33 return cals, nil | |
34 } | |
35 | |
36 func (c *MongoClient) GetOneCal(calId string) (MongoCal, error) { | |
37 res := c.calsCollection.FindOne(c.ctx, bson.M{"_id": calId}) | |
38 var cal MongoCal | |
39 err := res.Decode(&cal) | |
40 return cal, err | |
41 } | |
42 | |
43 func (c *MongoClient) UpsertOneCal(cal MongoCal) error { | |
44 filter := bson.M{"_id": cal.Url} | |
45 update := bson.M{"$set": cal} | |
46 _, err := c.calsCollection.UpdateOne(c.ctx, filter, update, | |
47 options.Update().SetUpsert(true)) | |
48 if err != nil { | |
49 return err | |
50 } | |
51 return nil | |
52 } | |
53 | |
54 func (c *MongoClient) DeleteCalsNotInSet(urlsToKeep map[string]bool) error { | |
55 curs, err := c.calsCollection.Find(c.ctx, bson.M{}) | |
56 if err != nil { | |
57 return err | |
58 } | |
59 defer curs.Close(c.ctx) | |
60 | |
61 for curs.Next(c.ctx) { | |
62 var doc bson.M | |
63 err = curs.Decode(&doc) | |
64 if err != nil { | |
65 return err | |
66 } | |
67 calUrl, ok := doc["_id"].(string) | |
68 if !ok { | |
69 continue | |
70 } | |
71 if !urlsToKeep[calUrl] { | |
72 log.Println(" cleaning up", calUrl) | |
73 _, err = c.calsCollection.DeleteOne(c.ctx, bson.M{"_id": doc["_id"]}) | |
74 if err != nil { | |
75 return err | |
76 } | |
77 } | |
78 } | |
79 return curs.Err() | |
80 } |