lundi 23 février 2015

Play! - how to reuse common logic for path fragment



I am currently using Play 2.3 and I have to deal with similar URL mappings:



GET /api/companyId/employeeId/tasks
GET /api/companyId/employeeId/timesheets
etc.


In every GET I need to perform similar logic:



public Promise<Result> getEmployeeTimesheets(Long companyId, Long employeeId) {
return promise(() -> {
if (!companyRepository.one(companyId).isPresent()) {
return notFound("Company doesn't exist");
}
if (!employeeRepository.one(employeeId).isPresent()) {
return notFound("Employee doesn't exist");
}
if (!employeeRepository.employeeWorksForCompany(companyId, employeeId)) {
return forbidden("Employee doesn't work for this company");
}

// some actual logic here
});
}


This code repeats over and over again. So far I used plain old inheritance and moved that repeating code into the parent controller class. It gets the job done, but it certainly isn't perfect solution (because I have to invoke parent method and inspect results manually in every controller action).


Is there some more declarative approach in Play that would automatically handle fragment of URL (/api/companyId/employeeId in our case) and either delegate the execution to an appropriate controller, or return an error response (for example 404 - Not Found).




Aucun commentaire:

Enregistrer un commentaire