Reputation: 183
I have this code.I want to have some rows in JSON,to find it Im trying to use criteria. I want render each case as json. Example: I want the row of my table that have Name:"pepito" .if I put params.nombre, but I want this only this row in JSON how can I do that? Im trying to do that with findbyNombre(params.nombre) but if I put some if/else with his conditions it doesnt found. Please,can somebody help me????I have to give my code for a job and Im lost!!! THANKS!
case "GET":
def criterios=CatalogoJson.createCriteria().list() {
if (params.nombre) {
eq('nombre', params.nombre)
// render CatalogoJson.findByNombre(params.nombre)as JSON
}
if(params.id) {
eq('id', CatalogoJson.findById(params.id))
}
}
render criterios as JSON
break
Upvotes: 1
Views: 554
Reputation: 50245
I might not have got the question correctly as to what is expected. My assumption is that, you would have either of the params
(either nombre or the Id or both) available in the request. Based on that assumption you can have the criteria implemented as below. Note:- I used toInteger()
as you mentioned the datatype as int
, generally ids
are Long
in conjunction with GORM and Hibernate persistence layer.
def criterios = CatalogoJson.createCriteria().listDistinct {
if(params.id) {
idEq(params.id.toInteger())
}
if (params.nombre) {
eq('nombre', params.nombre)
}
}
render criterios as JSON
UPDATE
Ok let me try this one more time. Again if I have followed you incorrectly, let me know.
The way you are expecting to map url is not RESTful. Instead, there is one best way to implement what you are expecting in the REST service:-
Pleasant way OR I-like-it-this-way
The url mapping should look like
"/catalog/$id?"(resource: 'catalog')
//Controller Action:-
def show(){
def criterios = CatalogoJson.createCriteria().list {
if(params.id) { //check 1
idEq(params.id.toInteger())
} else if(params.name) { //check 2
eq('name', params.name)
} else if(params.year){ //check 3
eq('year', params.year)
} else if(params.others){ //check 4
eq('others', params.others)
} //so on an so forth //Can also use Switch case if you want
}
render criterios as JSON
}
Use case:-
http://mydomain.com/catalog/134 --> should set the id
to 134 and check 1 will be evaluated
http://mydomain.com/catalog?name=Pep --> should set the name
to Pep
and check 2 will be evaluated
http://mydomain.com/catalog?year=1987 --> should set the year
to params as 1987
and check 3 will be evaluated
Inference-
Use of named query parameters to itemize your parameters with respect to your need in REST service and domain. If you want to use unnamed parameters then the url mapping would look like:
"/catalog/$id/$name?/$year?/$others?"(resource: 'catalog')
The problem in this approach is that your url should look like
http://mydomain.com/catalog/134
http://mydomain.com/catalog/134/Pep
http://mydomain.com/catalog/134/Pep/1987
Your optional parameters are no more optional. Have a look at Optional Variables in URL mapping
Upvotes: 2