/
packages.go
88 lines (75 loc) · 2.04 KB
/
packages.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
package packages
import (
"context"
"github.com/samirkape/awesome-go-bot/internal/services/packages/analytics/inmemory"
"github.com/samirkape/awesome-go-bot/internal/services/packages/mongodb"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"log"
"sort"
)
var cache inmemory.AllPackages
type Service interface {
GetAllPackages() inmemory.AllPackages
}
type Client struct {
client *mongo.Client
}
func NewService(client *mongo.Client) Service {
return &Client{client: client}
}
func (c *Client) GetAllPackages() inmemory.AllPackages {
if cache == nil {
collections := c.listCollections(mongodb.TABLENAME)
packages := make(map[inmemory.CategoryName][]inmemory.Package)
for _, collectionName := range collections {
p, err := c.getPackagesByCollectionName(mongodb.TABLENAME, collectionName)
if err != nil {
return nil
}
// sort before adding to map
sort.Slice(p, func(i, j int) bool {
return p[i].Stars > p[j].Stars
})
packages[inmemory.CategoryName(collectionName)] = p
}
cache = packages
}
return cache
}
func (c *Client) listCollections(databaseName string) (collections []string) {
database := c.client.Database(databaseName)
// List the collections
collections, err := database.ListCollectionNames(context.Background(), bson.D{})
if err != nil {
log.Fatal(err)
}
return collections
}
func (c *Client) getPackagesByCollectionName(databaseName string, collectionName string) ([]inmemory.Package, error) {
filter := bson.D{}
ctx := context.TODO()
packages := []inmemory.Package{}
database := c.client.Database(databaseName).Collection(collectionName)
cursor, err := database.Find(ctx, filter)
if err != nil {
return nil, err
}
defer func(cur *mongo.Cursor, ctx context.Context) {
err := cur.Close(ctx)
if err != nil {
log.Fatal(err)
}
}(cursor, ctx)
for cursor.Next(ctx) {
var p inmemory.Package
err := cursor.Decode(&p)
if err != nil {
return nil, err
} else {
p.Category = collectionName
packages = append(packages, p)
}
}
return packages, nil
}