嵌套的RESTful资源

时间:2014-03-26 23:29:33

标签: rest grails

我使用Grails在2.3中引入的REST支持。我的应用包括以下域类:

@Resource(formats=['json', 'xml'])
class Sensor {
    String name
    static hasMany = [metrics: Metric]
}

@Resource(formats=['json', 'xml'])
class Metric {

    String name
    String value

    static belongsTo = [sensor: Sensor]
}

UrlMappings.groovy中,我定义了以下嵌套的RESTful URL映射:

"/api/sensors"(resources: 'sensor') {
    "/metrics"(resources: "metric")
}

如果我导航到网址/api/sensors/1/metrics,我希望响应显示与ID为{1}的所有Metric个实例,但实际上它会返回所有Sensor实例(最多10个)

  • 是否存在仅返回与特定Metric实例关联的Metric个实例的网址(未实现我自己的控制器)?
  • 有没有办法覆盖10个结果的默认限制(不向请求添加Sensor参数)?

1 个答案:

答案 0 :(得分:6)

看起来并非如此简单。 :)如果运行此命令,我们可以得到生动的图片:

grails url-mapping-report

Controller: metric
 |   GET    | /api/sensors/${sensorId}/metrics           | Action: index  |
 |   GET    | /api/sensors/${sensorId}/metrics/create    | Action: create |
 |   POST   | /api/sensors/${sensorId}/metrics           | Action: save   |
 |   GET    | /api/sensors/${sensorId}/metrics/${id}     | Action: show   |
 |   GET    | /api/sensors/${sensorId}/metrics/${id}/edit| Action: edit   |
 |   PUT    | /api/sensors/${sensorId}/metrics/${id}     | Action: update |
 |  DELETE  | /api/sensors/${sensorId}/metrics/${id}     | Action: delete |

因此,我们至少需要MetricController继承RestfulController并覆盖index()来对Metric进行额外检查,并根据Sensor返回列表如下图所示:

class MetricController extends RestfulController<Metric> {
    static responseFormats = ['json', 'xml']

    MetricController() {
        super(Metric)
    }

    @Override
    def index() {
        def sensorId = params.sensorId
        respond Metric.where {
            sensor.id == sensorId
        }.list()
    }
}

以上更改将在点击时为/api/sensors/1/metrics提供预期结果(包括对分页结果的限制)。