Skip to content

Support for passing custom values/services into Snippet classes #308

@jmisur

Description

@jmisur

In our auto-documentation extension https://github.com/ScaCap/spring-auto-restdocs we are trying to automate documentation as much as possible by introspecting code. For this we created extensions of Snippets which are dependent on some common services, such as jackson ObjectMapper, custom constraints & javadoc reader, having HandlerMethod available etc.

For passing these common components around, we are doing little hack by putting custom attributes inside MockHttpServletRequest, then inside the Snippet class getting them from Operation attributes:

    public static ObjectMapper getObjectMapper(Operation operation) {
        return (ObjectMapper) operation.getAttributes().get(ObjectMapper.class.getName());
    }

    public static void setObjectMapper(MockHttpServletRequest request, ObjectMapper objectMapper) {
        ((Map) request.getAttribute(ATTRIBUTE_NAME_CONFIGURATION))
                .put(ObjectMapper.class.getName(), objectMapper);
    }

https://github.com/ScaCap/spring-auto-restdocs/blob/master/spring-auto-restdocs-core/src/main/java/capital/scalable/restdocs/OperationAttributeHelper.java

We are setting it for every request using custom ResultHandler and alwaysDo mechanism.

        public void handle(MvcResult result) throws Exception {
            setHandlerMethod(result.getRequest(), (HandlerMethod) result.getHandler());
            setObjectMapper(result.getRequest(), objectMapper);
            ...

https://github.com/ScaCap/spring-auto-restdocs/blob/master/spring-auto-restdocs-core/src/main/java/capital/scalable/restdocs/jackson/JacksonResultHandlers.java

Because we need custom data for every request, such as request pattern and HandlerMethod, we cannot configure these things statically during Snippet class creation.

As this mechanism is basically a hack to inner workings of spring-restdocs (discovered how these attributes are passed around by digging in source code) and it's prone to change as it's internal api, it would be great if this framework offers customization of such things out of the box. Could be still using these attributes internally but having some convenient public api.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions