Skip to content
This repository has been archived by the owner on Aug 28, 2024. It is now read-only.

Added a KB style document about RestMapper #462

Merged
merged 1 commit into from
Dec 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions docs/RestMapper.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# RestMapper

## Using the RestMapper in a reconciler.

It's sometimes necessary to access the RestMapper in your reconciler. The RestMapper's
purpose is to map between the `R` (Resource) in `GVR` and the `K` (Kind) in `GVK`.

Unfortunately `rtesting` (Reconciler-Runtime's [testing](../README.md#testing)) cannot
populate the RestMapper automatically. The information for this mapping is (typically)
generated by controller-gen and placed into manifests.

For RestMapper to work, you will need to populate the RestMapper with the GVK you want
it to resolve.

### Example: Using the resource guesser

[DefaultRESTMapper.Add](https://pkg.go.dev/k8s.io/apimachinery/pkg/api/[email protected]#DefaultRESTMapper.Add) adds the GVK
with a guessed singular and plural resource name. (See [UnsafeGuessKindToResource](https://pkg.go.dev/k8s.io/apimachinery/pkg/api/[email protected]#UnsafeGuessKindToResource)
for how this is done)

```
rts.Run(t, scheme, func(t *testing.T, rtc *rtesting.ReconcilerTestCase, c reconcilers.Config) reconcile.Reconciler {
gvk := schema.GroupVersionKind{
Group: "example.com",
Version: "v1alpha1",
Kind: "Widget",
}
restMapper := c.RESTMapper().(*meta.DefaultRESTMapper)
restMapper.Add(gvk, meta.RESTScopeNamespace)
return widget.Reconciler(c)
})
```

### Example: Using an explicit mapping

[DefaultRESTMapper.AddSpecific](https://pkg.go.dev/k8s.io/apimachinery/pkg/api/[email protected]#DefaultRESTMapper.AddSpecific)
adds the GVK with an explicit resource name.

```
rts.Run(t, scheme, func(t *testing.T, rtc *rtesting.ReconcilerTestCase, c reconcilers.Config) reconcile.Reconciler {
gvk := schema.GroupVersionKind{
Group: "example.com",
Version: "v1alpha1",
Kind: "Widget",
}
gvrSingular := schema.GroupVersionKind{
Group: "example.com",
Version: "v1alpha1",
Resource: "widget",
}
gvrPlural := schema.GroupVersionKind{
Group: "example.com",
Version: "v1alpha1",
Resource: "widgets",
}

restMapper := c.RESTMapper().(*meta.DefaultRESTMapper)
restMapper.AddSpecific(gvk, gvrSingular, gvrPlural, meta.RESTScopeNamespace)
return widget.Reconciler(c)
})
```
Loading