torbenmerrald
torbenmerrald

Reputation: 45

Grails UrlMappings for Rest and other actions

I have a controller which is primarily used for REST communication using the show, update, save and delete actions. This is mapped accordingly in the UrlMappings.groovy file and works just fine.

I then have a need for calling the getAccountTypesByEnv action in the same controller, but I have had some trouble to set up a syntax which actually works.

The below definition works, but I was wondering whether there is an easier and more correct way of doing it.

"/ext/accounttype/$id?"(controller: "accountType") {
    action = [GET: 'show', PUT: 'update', POST: 'save', DELETE: 'delete']
    "/ext/accounttype/getAccountTypesByEnv"(controller: "accountType", action: "getAccountTypesByEnv")
}

Update

I ended up dividing this into 2 separate generic mappings as displayed below:

"/ext/$controller/$id?" {
     action = [GET: 'show', PUT: 'update', POST: 'save', DELETE: 'delete']
}

"/ext/$controller/action/$customAction?" {
     action = { return params.customAction }
}

Upvotes: 1

Views: 456

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

You can define in your UrlMappings.groovy like:

 "/ext/$controller/$resourceId?/$customAction?" {
    action = {
        Map actionMethodMap = [GET: params.resourceId ? "show" : "index", POST: "save", PUT: "update", DELETE: "delete"]

        return params.customAction ?: actionMethodMap[request.method.toUpperCase()]
    }
    id = {
        if (params.resourceId == "action") {
            return params.id
        }
        return params.resourceId
    }
}

This is the most generic UrlMapping I think for now which you can use here in the following way:

GET     "/ext/accounttype" will call **index** action of AccounttypeController
POST    "/ext/accounttype" will call save action of AccounttypeController
PUT     "/ext/accounttype/14" will call update action of AccounttypeController with id 14
DELETE  "/ext/accounttype/14" will call update action of AccounttypeController with id 14
GET     "/ext/accounttype/14" will call show action of AccounttypeController with id 14
GET     "/ext/accounttype/action/getAccountTypesByEnv" will call getAccountTypesByEnv action of AccounttypeController with null id
GET     "/ext/accounttype/action/getAccountTypesByEnv?id=143" will call getAccountTypesByEnv action of AccounttypeController with id 143

Upvotes: 1

Related Questions