将自定义操作添加到Grails RestfulController

时间:2015-08-05 17:40:36

标签: rest grails groovy

我正在使用Grails RestfulController来满足以下端点:

    GET /dayoffs    index
    GET /dayoffs/${id}  show
    GET /dayoffs/create create
    GET /dayoffs/${id}/edit edit
    POST    /dayoffs    save
    PUT /dayoffs/${id}  update
    DELETE  /dayoffs/${id}  delete

    PUT /dayoffs/${id}/approve

Dayoffs是员工提出的休假请求。管理员可以对“批准”操作执行PUT请求。

如何让Grails RestfulController支持我的自定义'批准'请求?

仅供参考:我知道这不是'完全'宁静,但这是我项目的要求。如果无法使用RestfulController执行此操作,我会接受有关如何在我的Dayoffs RestfulController中保留标准rest方法的其他方式修补操作的建议。

1 个答案:

答案 0 :(得分:0)

You can always do it "by hand". Even then, things don't work quite the way I would like.

In UrlMappings, you probably have

static mappings = [
  "/dayoffs(resources: "dayoff") // Calls DayoffController
]

You can change that to

static mappings = [
  "/dayoffs(resources: "dayoff") {
    "/approve" (controller: "dayoff", action: "approve", method: "PUT")
  }
]

This will make sure that PUT requests to /dayoffs/13/approve will call your DayoffController's approve method with params.id set to 13.

Unfortunately, you will not be able to specify the requested format as part of the url with this (at least, I haven't been able to, even when using a mapping of "/approve(.$format)" instead).

If you find a better answer, please let me know!