I am creating connectors for REST API methods. Some methods has the same method name but performs different HTTP methods.
For example, createEntity( HttpMethod httpMethod, CreateEntity model )
can perform POST and GET only. What I want is to have an error when httpMethod
is supplied with PUT or DELETE. The allowed httpMethod
will depend every method. How can I do this validation inside CreateEntity.groovy
?
Here is the 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
}
this must be valid:
createEntity( HttpMethod.POST, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.GET, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
this should throw an error:
createEntity( HttpMethod.PUT, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
createEntity( HttpMethod.DELETE, new EntityQuery([ field1 : "field1", field2 : "field2" ]))
Is that what you're looking for:
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())
?
However it'd be better to expose public methods like createPostEntity
or createGetEntity
which will be accepting only EntityQuery
as an argument and HttpMethod
will be handled internally.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments