Implement Domain Service

Service Base

  • For each service there will be an abstract class Service Base generated in the SDK.

  • The Service Base provide access to the repository, entity builder, event builder and event producer.

  • The Service Base contains one abstract method named execute.

  • This execute method needs to be implemented in the generated implementaion file for the service.

Input & Output Entity

  • Service execute method will take modelled Input Entity as a paramter.

  • Service execute method will return modelled Output Entity as a return type.

Business Errors

  • If service is modelled with business errors, it will be added as throws declaration to service execute method.

Events

  • If service is modelled with business events, for each event there will be an inherited method in the service base class that takes the event as an input and publishes it.

  • It is also possible to publish events directly using EventProducerService.

Implementation Example

Example of Balance service implemenation file.

//... imports

@Service
public class BalanceService extends BalanceServiceBase {

	private static Logger log = LoggerFactory.getLogger(BalanceService.class);
	
	public BalanceService(DomainEntityBuilder entityBuilder, DomainEventBuilder eventBuilder, EventProducerService eventProducer, Repository repo) {
		super(entityBuilder, eventBuilder, eventProducer, repo);
	}

    // Example of a service implemenation logic
	@NewSpan
	@Override
	public Balance execute(CreditCard creditCard) throws CreditCardNotFoundError {

		log.info("BalanceService.execute()");
  
        // Use repository to get card instance
		Optional<Card> cardRootEntity = this.repo.getCc().getCard().findById(creditCard.getId());
		if(cardRootEntity.isPresent()) {

		  // Use Domain Entity Builder from base class to create an instance of Balance entity
		  Balance balance = this.entityBuilder.getCc().getBalance().build();
		  balance.setAvaliableBalance(cardRootEntity.getBalance());
		  balance.setHoldAmount(cardRootEntity.getHoldAmount());

		  return balance;
		} else {
			String errorMessage = String.format("Credit card with id %s not found" ,
			 creditCard.getId());
           throw new CreditCardNotFoundError(errorMessage);
		}
	}