Finding a RESTful interface implementation on Grails

I am creating a RESTful interface in a Grails 2.1.1 application. How do I perform search operations? I do not want to repeat the huge amount of code that my current thinking will require.

The server structure is quite normal Grails-MVC: domain classes represent data, controllers offer an interface, and services have business logic. I use command objects to bind data in controllers, but not for maintenance methods. Client is a web interface. My goal is to find search URLs as follows:

/cars/?q=generic+query+from+all+fields /cars/?color=red&year=2011 

(I know about the RESTfulness debate on this type of URL with query strings: RESTful URL design for search . Although I think this is the best model for my purpose, I am open to alternatives if they improve the API and implementation.)

As you can see from the code examples below, my problem is with the second kind of URL that is used to search the field. To implement such a search operation for several domain classes with a large number of fields, my method signatures will explode.

There is probably a β€œGroovy way”, but I'm still a bit n00b in the finer Groovy tricks :)

Domain:

 class Car { String color int year } 

Controller:

 class CarsController { def carService def list(ListCommand cmd) { def result if (cmd.q) { result = carService.search(cmd.q, cmd.max, cmd.offset, cmd.order, cmd.sort) } else { result = carService.search(cmd.color, cmd.year, cmd.max, cmd.offset, cmd.order, cmd.sort) } render result as JSON } class ListCommand { Integer max Integer offset String order String sort String q String color // I don't want this field in command int year // I don't want this field in command static constraints = { // all nullable } } // show(), save(), update(), delete() and their commands clipped } 

Services:

 class CarService { List<Car> search(q, max=10, offset=0, order="asc", sort="id") { // ... } List<Car> search(color, year, max=10, offset=0, order="asc", sort="id") { // ... } } 

UrlMappings:

 class UrlMappings { static mappings = { name restEntityList: "/$controller"(parseRequest: true) { action = [GET: "list", POST: "save"] } name restEntity: "/$controller/$id"(parseRequest: true) { action = [GET: "show", PUT: "update", POST: "update", DELETE: "delete"] } } } 
+4
source share
1 answer

You can get all of these parameters from params , for example:

 result = carService.search(params.color, params.year as Integer, cmd.max, cmd.offset, cmd.order, cmd.sort) 

All params map values ​​are strings, so you should convert them to the appropriate data structures in the controller (and better check that params.year is the actual number)


Update

If you do not want to write field names, you can pass it as a map:

 resutl = carService.search(params) 

Where

 List<Car> search(Map params) 
+1
source

All Articles