我正在为REST API方法创建连接器。某些方法具有相同的方法名称,但执行不同的HTTP方法。
例如,createEntity( HttpMethod httpMethod, CreateEntity model )
只能执行POST和GET。我想要的是在PUT或DELETE提供httpMethod
时出错。允许的httpMethod
取决于每种方法。如何在CreateEntity.groovy
内进行此验证?
这是 HttpMethod.groovy
public enum HttpMethod {
POST,
DELETE,
GET,
PUT,
HEAD,
TRACE,
CONNECT,
PATCH
}
CreateEntity.groovy
private String field1;
private String field2;
//write here that only POST and GET are allowed
Connector.groovy
def createEntityQuery ( HttpMethod httpMethod, CreateEntityQuery model ) {
//perform operations
}
这必须是有效的:
createEntity( HttpMethod.POST, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.GET, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
这会引发错误:
createEntity( HttpMethod.PUT, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.DELETE, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
答案 0 :(得分:0)
这就是你要找的东西:
public enum HttpMethod {
POST,
DELETE,
GET,
PUT,
HEAD,
TRACE,
CONNECT,
PATCH
}
class EntityQuery {
String field1
String field2
}
def createEntity(HttpMethod h, EntityQuery q) {
if(!(h in [HttpMethod.POST, HttpMethod.GET])) {
throw new Exception('Only POST and GET methods allowed')
}
}
createEntity(HttpMethod.PUT, new EntityQuery())
但是,最好公开createPostEntity
或createGetEntity
这样的公共方法,这些方法仅接受EntityQuery
作为参数,HttpMethod
将在内部处理