【发布时间】:2014-07-19 09:21:17
【问题描述】:
我正在寻找最佳实践/解决方案,以使“响应”方法在生成的 json 中生成额外的元数据以及从数据库中获取的实体集合。
基本上,我想在使用 angularJS 和 Restangular 插件构建的前端单页应用程序 (SPA) 中使用该元数据来实现分页。
PS:angularJS 的 $resource 或 Restangular 期望收集结果为 JS 数组。
Standard Grails JsonCollectionRenderer/JsonRenderer 会忽略在 map 参数中提供给“respond”的元数据。
我遇到了以下实现自定义 JsonRenderer 的文章,但我正在寻找更简单/灵活的解决方案,通过在 resources.groovy 中调整自定义 JsonCollectionRenderer 来“响应”输出元数据
http://groovyc.net/non-trivial-restful-apis-in-grails-part-2/
我的 RestfulController:
@Secured(value=["hasRole('ROLE_USER')"])
class DrugController extends RestfulController<Drug> {
static scaffold = true
static responseFormats = ['html', 'json', 'xml', 'hal']
static allowedMethods = [show: "GET"]
DrugController() {
super(Drug, true)
}
@Override
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
// We pass which fields to be rendered with the includes attributes,
// we exclude the class property for all responses. ***when includes are defined excludes are ignored.
//params.fetch = [recordTypeRs:"eager"] from params.fields???
respond resource.list(params),
[includes: includeFields, excludes: ['class', 'errors', 'version'],
metadata: [total: countResources(), psize: params.max, offset: params.offset?:0],
model: [("${resourceName}InstanceCount".toString()): countResources()]]
}
@Override
def show(Drug drug) {
JSON.use("deep") {
respond drug,
[includes: includeFields, excludes: ['class', 'errors', 'version']]
}
}
private getIncludeFields() {
params.fields?.tokenize(',')
}
def search(Integer max) {
params.max = Math.min(max ?: 10, 100)
def c = Drug.createCriteria()
def results = c.list(params) {
//Your criteria here with params.q
and {
like('ndc', params.ndc?params.ndc+'%':'%')
like('recordTypeJ.j017', params.labelerName?'%'+params.labelerName+'%':'%')
like('recordTypeE.e017', params.productName?'%'+params.productName+'%':'%')
}
//cache(true)
}
log.debug(results.totalCount)
respond results, model:[drugCount: results.totalCount]
}
}
我的 resources.groovy 中有以下内容。
// register Renderers/CollectionRenderers for all domain classes in the application.
for (domainClass in grailsApplication.domainClasses) {
"json${domainClass.shortName}CollectionRenderer"(JsonCollectionRenderer, domainClass.clazz)
"json${domainClass.shortName}Renderer"(JsonRenderer, domainClass.clazz)
"hal${domainClass.shortName}CollectionRenderer"(HalJsonCollectionRenderer, domainClass.clazz)
"hal${domainClass.shortName}Renderer"(HalJsonRenderer, domainClass.clazz)
}
【问题讨论】:
标签: json rest grails pagination metadata