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
Services:
class CarService { List<Car> search(q, 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"] } } }