【问题标题】:nested RESTful resources嵌套的 RESTful 资源
【发布时间】:2014-03-26 23:29:32
【问题描述】:

我正在使用 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")
}

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

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

【问题讨论】:

  • 关于在使用资源时更改限制,答案是否定的。之前已经对此进行了讨论。这种设计选择背后的原因是 Resource 的设计目的是快速和简单,生成和修改控制器作为下一级定制。我之前对此的回答指向 Grails 源代码,以证明 Resource 不允许这种自定义。
  • @JoshuaMoore 谢谢,你知道是否有可能为单个 Sensor 实例获取 Metric 实例?
  • 从未使用过它们,但根据文档:grails.org/doc/2.3.x/guide/single.html#restfulMappings 这似乎是你所拥有的。
  • 让我们知道是否有比提供的答案更好的方法。 :)

标签: rest grails


【解决方案1】:

看起来没那么简单。 :) 如果运行这个命令,我们可以得到一幅生动的画面:

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 提供预期结果(包括对分页结果的限制)。

【讨论】:

  • 这是最不冗长的方法吗?这怎么不是默认功能._.
猜你喜欢
  • 2017-12-17
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多