嵌套的 RESTful 资源 [英] nested RESTful resources
问题描述
我正在使用 Grails 在 2.3 中引入的对 REST 的支持.我的应用包括以下域类:
I'm using the support for REST introduced by Grails in 2.3. My app includes the following domain classes:
@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 映射:
And in UrlMappings.groovy
I've defined the following nested RESTful URL mappings:
"/api/sensors"(resources: 'sensor') {
"/metrics"(resources: "metric")
}
如果我导航到 URL /api/sensors/1/metrics
我希望响应显示与 Sensor
Metric 实例> ID 为 1,但实际上它返回所有 Metric
实例(最多 10 个)
If I navigate to the URL /api/sensors/1/metrics
I expect the response to show all Metric
instances associated with the Sensor
with ID 1, but in fact it returns all Metric
instances (up to a limit of 10)
- 是否有一个 URL 将仅返回与特定
Sensor
实例相关联的Metric
实例(不实现我自己的控制器)? - 有没有办法覆盖 10 个结果的默认限制(不向请求添加
max
参数)?
- Is there a URL that will return only
Metric
instances associated with a particularSensor
instance (without implementing my own controller)? - Is there a way to override the default limit of 10 results (without adding a
max
parameter to the request)?
推荐答案
看起来没那么简单.:) 如果运行这个命令,我们可以得到一个生动的画面:
Looks like it isn't that simple. :) We can get a vivid picture if this command is run:
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
的返回列表如下所示:
So, we would at least need a MetricController
inheriting RestfulController
and override index()
to do an additional check for Metric
and return list based on Sensor
as shown below:
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
提供预期结果(包括对分页结果的限制).
Above changed would provide the expected result (including the restriction on paginated results) for /api/sensors/1/metrics
when hit.
这篇关于嵌套的 RESTful 资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!