使用枚举限制允许的httpMethods

时间:2015-06-21 08:27:50

标签: rest groovy enums

我正在为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" ]))

1 个答案:

答案 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())

但是,最好公开createPostEntitycreateGetEntity这样的公共方法,这些方法仅接受EntityQuery作为参数,HttpMethod将在内部处理