Skip to content

Commit

Permalink
Added a KB style document about RestMapper (#462)
Browse files Browse the repository at this point in the history
  • Loading branch information
squeedee committed Dec 8, 2023
1 parent 3ecc1b0 commit 7b12bc5
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions docs/RestMapper.md
@@ -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/meta@v0.28.4#DefaultRESTMapper.Add) adds the GVK
with a guessed singular and plural resource name. (See [UnsafeGuessKindToResource](https://pkg.go.dev/k8s.io/apimachinery/pkg/api/meta@v0.28.4#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/meta@v0.28.4#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 7b12bc5

Please sign in to comment.