yahehe / Nancy.Swagger

Nancy plugin for generated API documentation in Swagger format.
MIT License
133 stars 60 forks source link

Allow SwaggerResponse attribute at class level? #158

Open vincentparrett opened 6 years ago

vincentparrett commented 6 years ago

Currently, the SwaggerResponse is only valid for methods. As I get deeper into instrumenting my modules with the Nancy.Swagger attributes, I'm finding some modules have common attributes on every method, for example :

[SwaggerResponse(HttpStatusCode.Forbidden, Model = typeof(ForbiddenModel))]

is on pretty much every method I have instrumented so far.

Would it make sense to allow the SwaggerResponse at the method level?

jnallard commented 6 years ago

Yeah, it would be helpful.

A function like this would allow it to work without changing the existing flow (or another extension method).

private IEnumerable<T> GetCustomAttributes<T>(MethodInfo handler) where T: Attribute
{
    var attributes = handler.GetCustomAttributes<T>();
    return attributes.Concat(handler.DeclaringType.GetTypeInfo().GetCustomAttributes<T>());
} 

You would just need to replace the current GetCustomAttributes in AnnotatedOperation. And once you allowed the Attributes to be applied to classes, it should just work. Might be good to allow Parameters, such as for constant headers, and Tags as well, (although Tags is a bit trickier).

Feel free to try and implement! Otherwise I'll get to it later.

vincentparrett commented 6 years ago

It's a bit more complicated than that, as you probably want to deal with duplicates for a start.

jnallard commented 6 years ago

True. There might be a response that you want for the whole module, but a certain route might want to override it.

That could still be implemented using my code. Since the method attributes would be first in the IEnumerable, you could just ignore any duplicate responses afterwards. But what counts as a duplicate response? Something with the same status code? We didn't have that limit before, so that might break things.

Maybe just another method attribute that says to skip the class attributes.

vincentparrett commented 6 years ago

I think a duplicate response would be by status code and model.

I think we should keep it simple, if it's on the class it's on all methods, otherwise you have to use method attributes.