I am currently developing an API which needs to "extend" its own data (my database) with the data I receive from another API. I have an inventory class/aggregate in the domain layer with a repository interface which is implemented in the infrastructure layer.
Now I have injected via Dependency Injection both the Entity Manager for my own database as well as the RestClient for the external API.
public class RestInventoryRepository implements InventoryRepository {
@RestClient
@Inject
InventoryRestClient inventoryRestClient;
@Inject
EntityManager eM;
In the repository method implementation I first call the rest client and receive its representation of the requested inventory. I then map it to my inventory class with an Object Mapper. After that I try to get the additional information from my boxInventory by the same inventory id and then append it to the earlier received inventory.
The result is a rather big method which only gets bigger with other additions. My question now is if there is a good practise to handle situations like that? I found the API Composition pattern but I am not sure if I can handle mixing a database with a API the same way as if mixing different APIs.
public Optional<Inventory> findInventoryById(String inventoryId) {
JSONObject inventoryJSON = inventoryRestClient.getInventoryById(inventoryId);
if (inventoryJSON == null) {
return Optional.empty();
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Inventory inventory = objectMapper.convertValue(inventoryJSON, Inventory.class);
//extracts boxTagInventory
TypedQuery<BoxInventory> typedQuery =
eM.createQuery("FROM BoxInventory WHERE INVENTORY_ID = :inventoryId",
BoxInventory.class);
typedQuery.setParameter("inventoryId", inventory.inventoryId());
List<BoxInventory> resultSet = typedQuery.getResultList();
if(resultSet.isEmpty()){
return Optional.empty();
}
inventory.addBoxInventory(resultSet.get(0));
return Optional.of(inventory);
}