@@ -62,3 +62,68 @@ As the deleted comments request, run `make manager manifests` to regenerate some
62
62
git add .
63
63
git commit -m " Added cluster types"
64
64
```
65
+
66
+ # Registering APIs in the scheme
67
+
68
+ To enable clients to encode and decode your API, your types must be able to be registered within a [ scheme] .
69
+
70
+ [ scheme ] : https://pkg.go.dev/k8s.io/apimachinery/pkg/runtime#Scheme
71
+
72
+ By default, Kubebuilder will provide you with a scheme builder like:
73
+
74
+ ``` go
75
+ import " sigs.k8s.io/controller-runtime/pkg/scheme"
76
+
77
+ var (
78
+ // SchemeBuilder is used to add go types to the GroupVersionKind scheme
79
+ SchemeBuilder = &scheme.Builder {GroupVersion: GroupVersion }
80
+
81
+ // AddToScheme adds the types in this group-version to the given scheme.
82
+ AddToScheme = SchemeBuilder .AddToScheme
83
+ )
84
+ ```
85
+
86
+ and scheme registration that looks like:
87
+
88
+ ``` go
89
+ func init () {
90
+ SchemeBuilder.Register (&Captain{}, &CaptainList{})
91
+ }
92
+ ```
93
+
94
+ This pattern introduces a dependency on controller-runtime to your API types, which is discouraged for
95
+ API packages as it makes it more difficult for consumers of your API to import your API types.
96
+ In general, you should minimise the imports within the API folder of your package to allow your API types
97
+ to be imported cleanly into other projects.
98
+
99
+ To mitigate this, use the following schemebuilder pattern:
100
+
101
+ ``` go
102
+ import " k8s.io/apimachinery/pkg/runtime"
103
+
104
+ var (
105
+ // schemeBuilder is used to add go types to the GroupVersionKind scheme.
106
+ schemeBuilder = runtime.NewSchemeBuilder (addKnownTypes)
107
+
108
+ // AddToScheme adds the types in this group-version to the given scheme.
109
+ AddToScheme = schemeBuilder.AddToScheme
110
+
111
+ objectTypes = []runtime.Object {}
112
+ )
113
+
114
+ func addKnownTypes (scheme *runtime .Scheme ) error {
115
+ scheme.AddKnownTypes (GroupVersion, objectTypes...)
116
+ metav1.AddToGroupVersion (scheme, GroupVersion)
117
+ return nil
118
+ }
119
+ ```
120
+
121
+ and register types as below:
122
+
123
+ ``` go
124
+ func init () {
125
+ objectTypes = append (objectTypes, &Captain{}, &CaptainList{})
126
+ }
127
+ ```
128
+
129
+ This pattern reduces the number of dependencies being introduced into the API package within your project.
0 commit comments