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

Commit

Permalink
Added a KB style document about RestMapper
Browse files Browse the repository at this point in the history
  • Loading branch information
Rasheed Abdul-Aziz committed Dec 6, 2023
1 parent e22ffba commit 4f542d6
Showing 1 changed file with 61 additions and 0 deletions.
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)
})
```

0 comments on commit 4f542d6

Please sign in to comment.