| 1 | # API Core |
| 2 | |
| 3 | contains central elements of any API functionality, such as Exception mappers, etc. |
| 4 | |
| 5 | ## Using a `DtoTransformer` |
| 6 | |
| 7 | Let's assume that there is a controller class `ExampleApiController` with at least a `GET` endpoint |
| 8 | `GET /api/v1/example/objects` which returns a list of `ExampleObject`s. |
| 9 | And there would also be an `ExampleObjectDto`. All these things are implemented in an |
| 10 | `:extensions:api:example` extension. |
| 11 | |
| 12 | 1. Create a `ExampleObjectTransformer`: |
| 13 | |
| 14 | ```java |
| 15 | public class ExampleObjectTransformer implements DtoTransformer<ExampleObject, ExampleObjectDto>{ |
| 16 | // implementation |
| 17 | } |
| 18 | ``` |
| 19 | |
| 20 | 2. Register the transformer in your `ExampleApiExtension`: |
| 21 | ```java |
| 22 | //ExampleApiExtension.java |
| 23 | |
| 24 | public class ExampleApiExtension implements ServiceExtension{ |
| 25 | @Inject |
| 26 | private TypeTransformerRegistry registry; |
| 27 | |
| 28 | @Inject |
| 29 | private WebService webService; |
| 30 | |
| 31 | @Override |
| 32 | public void initialize(ServiceExtensionContext context){ |
| 33 | //register the transformer |
| 34 | var transformer = new ExampleObjectTransformer(/*params*/); |
| 35 | registry.register(transformer); |
| 36 | |
| 37 | //register controller |
| 38 | var ctrl= new ExampleApiController(registry); |
| 39 | webService.registerResource(ctrl); |
| 40 | } |
| 41 | } |
| 42 | ``` |
| 43 | |
| 44 | 3. Use the transformer in the controller: |
| 45 | |
| 46 | ```java |
| 47 | |
| 48 | import java.util.stream.Collectors; |
| 49 | |
| 50 | public class ExampleApiController { |
| 51 | // ... |
| 52 | |
| 53 | @GET |
| 54 | @Path(/*the path*/) |
| 55 | public List<ExampleObjectDto> getAll() { |
| 56 | |
| 57 | Stream<ExampleObject> objects = fetchFromSomewhere(); |
| 58 | |
| 59 | // not shown: error/failure handling |
| 60 | return objects.map(o -> registry.transform(o, ExampleObjectDto.class)) |
| 61 | .filter(AbstractResult::succeeded) |
| 62 | .map(AbstractResult::getContent) |
| 63 | .collect(Collectors.toList()); |
| 64 | |
| 65 | } |
| 66 | |
| 67 | } |
| 68 | ``` |