Add your own mediator for the Route parameter of some type of object in Play scala

Well, I want to replace my String parameter from the next Play scala Route with my own object, say, “MyObject”

From GET /api/:id controllers.MyController.get(id: String) To GET /api/:id controllers.MyController.get(id: MyOwnObject) 

Any idea on how to do this would be appreciated.

+5
source share
3 answers

Use PathBindable to bind parameters from a path, not from a query. An example implementation for binding identifiers from a path, separated by a comma (without error handling):

 public class CommaSeparatedIds implements PathBindable<CommaSeparatedIds> { private List<Long> id; @Override public IdBinder bind(String key, String txt) { if ("id".equals(key)) { String[] split = txt.split(","); id = new ArrayList<>(split.length + 1); for (String s : split) { long parseLong = Long.parseLong(s); id.add(Long.valueOf(parseLong)); } return this; } return null; } ... } 

Example path:

 /data/entity/1,2,3,4 

Example route input:

 GET /data/entity/:id controllers.EntityController.process(id: CommaSeparatedIds) 
+1
source

So, I wrote my own "MyOwnObject". Another way to implement PathBindable is to bind an object.

 object Binders { implicit def pathBinder(implicit intBinder: PathBindable[String]) = new PathBindable[MyOwnObject] { override def bind(key: String, value: String): Either[String, MyOwnObject] = { for { id <- intBinder.bind(key, value).right } yield UniqueId(id) } override def unbind(key: String, id: UniqueId): String = { intBinder.unbind(key, id.value) } } } 
+4
source

I'm not sure if it works to bind data in part of the URL path, but you can read the documents on QueryStringBindable if you can accept your data as query parameters.

+1
source

Source: https://habr.com/ru/post/1204869/


All Articles