-
Notifications
You must be signed in to change notification settings - Fork 11
/
reader.go
101 lines (76 loc) · 2.49 KB
/
reader.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package safe
import (
"context"
"fmt"
"github.com/cosi-project/runtime/pkg/controller"
"github.com/cosi-project/runtime/pkg/controller/generic"
"github.com/cosi-project/runtime/pkg/resource"
"github.com/cosi-project/runtime/pkg/state"
)
// ReaderGet is a type safe wrapper around reader.Get.
func ReaderGet[T resource.Resource](ctx context.Context, rdr controller.Reader, ptr resource.Pointer) (T, error) { //nolint:ireturn
got, err := rdr.Get(ctx, ptr)
if err != nil {
var zero T
return zero, err
}
result, ok := got.(T)
if !ok {
var zero T
return zero, fmt.Errorf("type mismatch: expected %T, got %T", result, got)
}
return result, nil
}
// ReaderGetByID is a type safe wrapper around reader.Get.
func ReaderGetByID[T generic.ResourceWithRD](ctx context.Context, rdr controller.Reader, id resource.ID) (T, error) { //nolint:ireturn
var r T
md := resource.NewMetadata(
r.ResourceDefinition().DefaultNamespace,
r.ResourceDefinition().Type,
id,
resource.VersionUndefined,
)
got, err := rdr.Get(ctx, md)
if err != nil {
var zero T
return zero, err
}
result, ok := got.(T)
if !ok {
var zero T
return zero, fmt.Errorf("type mismatch: expected %T, got %T", result, got)
}
return result, nil
}
// ReaderList is a type safe wrapper around Reader.List.
func ReaderList[T resource.Resource](ctx context.Context, rdr controller.Reader, kind resource.Kind, opts ...state.ListOption) (List[T], error) {
got, err := rdr.List(ctx, kind, opts...)
if err != nil {
var zero List[T]
return zero, err
}
if len(got.Items) == 0 {
var zero List[T]
return zero, nil
}
// Early assertion to make sure we don't have a type mismatch.
if _, ok := got.Items[0].(T); !ok {
var zero List[T]
return zero, fmt.Errorf("type mismatch on the first element: expected %T, got %T", got.Items[0], got)
}
return NewList[T](got), nil
}
// ReaderListAll is a type safe wrapper around Reader.List that uses default namaespace and type from ResourceDefinitionProvider.
func ReaderListAll[T generic.ResourceWithRD](ctx context.Context, rdr controller.Reader, opts ...state.ListOption) (List[T], error) {
var r T
md := resource.NewMetadata(
r.ResourceDefinition().DefaultNamespace,
r.ResourceDefinition().Type,
"",
resource.VersionUndefined,
)
return ReaderList[T](ctx, rdr, md, opts...)
}