|
| 1 | +# RestMapper |
| 2 | + |
| 3 | +## Using the RestMapper in a reconciler. |
| 4 | + |
| 5 | +It's sometimes necessary to access the RestMapper in your reconciler. The RestMapper's |
| 6 | +purpose is to map between the `R` (Resource) in `GVR` and the `K` (Kind) in `GVK`. |
| 7 | + |
| 8 | +Unfortunately `rtesting` (Reconciler-Runtime's [testing](../README.md#testing)) cannot |
| 9 | +populate the RestMapper automatically. The information for this mapping is (typically) |
| 10 | +generated by controller-gen and placed into manifests. |
| 11 | + |
| 12 | +For RestMapper to work, you will need to populate the RestMapper with the GVK you want |
| 13 | +it to resolve. |
| 14 | + |
| 15 | +### Example: Using the resource guesser |
| 16 | + |
| 17 | +[DefaultRESTMapper.Add ](https://pkg.go.dev/k8s.io/apimachinery/pkg/api/[email protected]#DefaultRESTMapper.Add) adds the GVK |
| 18 | +with a guessed singular and plural resource name. (See [UnsafeGuessKindToResource ](https://pkg.go.dev/k8s.io/apimachinery/pkg/api/[email protected]#UnsafeGuessKindToResource) |
| 19 | +for how this is done) |
| 20 | + |
| 21 | +``` |
| 22 | + rts.Run(t, scheme, func(t *testing.T, rtc *rtesting.ReconcilerTestCase, c reconcilers.Config) reconcile.Reconciler { |
| 23 | + gvk := schema.GroupVersionKind{ |
| 24 | + Group: "example.com", |
| 25 | + Version: "v1alpha1", |
| 26 | + Kind: "Widget", |
| 27 | + } |
| 28 | + restMapper := c.RESTMapper().(*meta.DefaultRESTMapper) |
| 29 | + restMapper.Add(gvk, meta.RESTScopeNamespace) |
| 30 | + return widget.Reconciler(c) |
| 31 | + }) |
| 32 | +``` |
| 33 | + |
| 34 | +### Example: Using an explicit mapping |
| 35 | + |
| 36 | +[DefaultRESTMapper.AddSpecific ](https://pkg.go.dev/k8s.io/apimachinery/pkg/api/[email protected]#DefaultRESTMapper.AddSpecific) |
| 37 | +adds the GVK with an explicit resource name. |
| 38 | + |
| 39 | +``` |
| 40 | + rts.Run(t, scheme, func(t *testing.T, rtc *rtesting.ReconcilerTestCase, c reconcilers.Config) reconcile.Reconciler { |
| 41 | + gvk := schema.GroupVersionKind{ |
| 42 | + Group: "example.com", |
| 43 | + Version: "v1alpha1", |
| 44 | + Kind: "Widget", |
| 45 | + } |
| 46 | + gvrSingular := schema.GroupVersionKind{ |
| 47 | + Group: "example.com", |
| 48 | + Version: "v1alpha1", |
| 49 | + Resource: "widget", |
| 50 | + } |
| 51 | + gvrPlural := schema.GroupVersionKind{ |
| 52 | + Group: "example.com", |
| 53 | + Version: "v1alpha1", |
| 54 | + Resource: "widgets", |
| 55 | + } |
| 56 | + |
| 57 | + restMapper := c.RESTMapper().(*meta.DefaultRESTMapper) |
| 58 | + restMapper.AddSpecific(gvk, gvrSingular, gvrPlural, meta.RESTScopeNamespace) |
| 59 | + return widget.Reconciler(c) |
| 60 | + }) |
| 61 | +``` |
0 commit comments