【发布时间】:2014-09-07 16:21:58
【问题描述】:
考虑这个现实世界的例子,它是通过 Rest Client Builder(Grails 插件)对同一个 REST 服务端点进行“GET”和“POST”调用而编写的代码。我不喜欢重复,因为标题和内容类型设置是相同的,但我不确定如何重构公共部分,因为它们正在调用传递给 get() 或 post() 方法调用的闭包上的方法.请在您的答案中提供一个很好地重构重复的具体示例。
private def doGetCall(String endpoint, def config) {
def response = new RestBuilder().get(config.baseURI+endpoint) {
contentType("application/json")
header("Authorization", "ApiKey " + config.base64EncodedApiKey)
header("ClientId", config.clientId)
}
handleResponse(response, config, endpoint);
return response;
}
private def doPostCall(String endpoint, def payload, def config) {
def response = new RestBuilder().post(config.baseURI+endpoint) {
contentType("application/json")
header("Authorization", "ApiKey " + config.base64EncodedApiKey)
header("ClientId", config.clientId)
json(payload)
}
handleResponse(response, config, endpoint, payload)
return response;
}
【问题讨论】: