scala - Requests / Responses DTO objects in Play -
i have simple question.
in java code, used use data transfer objects requests / responses.
for example, in spring webapp creating request dto,
public class saveofficerequest { private string officename; private string officephone; private string officeaddress; /* getters / setters */ }
after had controller "mapped" method like
@responsebody public saveofficeresponse saveoffice(@requestbody saveofficerequest) { ... }
.
every request json request. when controller method called converted request dto domain dto entities , business logic.
so!
should save practice in new scala project based on play framework?
case classes can used represent request , response objects. helps make api explicit, documented , type-safe, , isolate concerns, avoiding use domain objects directly in external interface.
for example, json endpoint, controller action use pattern this:
request.body.asjson.map { body => body.asopt[customerinsertrequest] match { case some(req) => { try { val toinsert = req.tocustomer() // convert request dto domain object val inserted = customersservice.insert(toinsert) val dto = customerdto.fromcustomer(inserted)) // convert domain object response dto val response = ... // convert dto json response ok(response) } catch { // handle exception , return failure response } } case none => badrequest("a customerinsertrequest entity expected in body.") } }.getorelse { unsupportedmediatype("expecting application/json request body.") }
Comments
Post a Comment