diff --git a/docs/RestMapper.md b/docs/RestMapper.md new file mode 100644 index 0000000..119083d --- /dev/null +++ b/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) + }) +``` \ No newline at end of file