/
runtime.go
101 lines (79 loc) · 2.7 KB
/
runtime.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
package repository
import (
"context"
"errors"
"github.com/konstellation-io/kdl-server/app/api/entity"
"github.com/konstellation-io/kdl-server/app/api/pkg/logging"
"github.com/konstellation-io/kdl-server/app/api/pkg/mongodb"
"github.com/konstellation-io/kdl-server/app/api/usecase/runtime"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
const (
runtimesCollName = "runtimes"
)
type runtimeDTO struct {
ID primitive.ObjectID `bson:"_id"`
Name string `bson:"name"`
Desc string `bson:"desc"`
Labels []string `bson:"labels"`
DockerImage string `bson:"docker_image"`
DockerTag string `bson:"docker_tag"`
}
type runtimeMongoDBRepo struct {
logger logging.Logger
collection *mongo.Collection
}
func (m *runtimeMongoDBRepo) Get(ctx context.Context, id string) (entity.Runtime, error) {
idFromHex, err := primitive.ObjectIDFromHex(id)
if err != nil {
return entity.Runtime{}, err
}
return m.findOne(ctx, bson.M{"_id": idFromHex})
}
func (m *runtimeMongoDBRepo) findOne(ctx context.Context, filters bson.M) (entity.Runtime, error) {
m.logger.Debugf("Finding one runtime by %q from database...", filters)
dto := runtimeDTO{}
err := m.collection.FindOne(ctx, filters).Decode(&dto)
if errors.Is(err, mongo.ErrNoDocuments) {
return entity.Runtime{}, entity.ErrRuntimeNotFound
}
return m.dtoToEntity(dto), err
}
// FindAll retrieves all projects.
func (m *runtimeMongoDBRepo) FindAll(ctx context.Context) ([]entity.Runtime, error) {
return m.find(ctx, bson.M{})
}
func (m *runtimeMongoDBRepo) find(ctx context.Context, filters bson.M) ([]entity.Runtime, error) {
m.logger.Debugf("Finding runtimes with filters %q...", filters)
var dtos []runtimeDTO
err := mongodb.Find(ctx, filters, m.collection, &dtos)
if err != nil {
return nil, err
}
return m.dtosToEntities(dtos), nil
}
func (m *runtimeMongoDBRepo) dtoToEntity(dto runtimeDTO) entity.Runtime {
p := entity.Runtime{
ID: dto.ID.Hex(),
Name: dto.Name,
Desc: dto.Desc,
Labels: dto.Labels,
DockerImage: dto.DockerImage,
DockerTag: dto.DockerTag,
}
return p
}
func (m *runtimeMongoDBRepo) dtosToEntities(dtos []runtimeDTO) []entity.Runtime {
result := make([]entity.Runtime, len(dtos))
for i, dto := range dtos {
result[i] = m.dtoToEntity(dto)
}
return result
}
// NewRuntimeMongoDBRepo implements runtimes.Repository interface.
func NewRuntimeMongoDBRepo(logger logging.Logger, client *mongo.Client, dbName string) runtime.Repository {
collection := client.Database(dbName).Collection(runtimesCollName)
return &runtimeMongoDBRepo{logger, collection}
}