在Spring Rest Docs中向基本URL添加路径吗?

时间:2018-12-24 21:30:40

标签: kotlin spring-webflux spring-restdocs

我具有以下用于Rest Docs的配置:

webTestClient = buildWebClient().mutate()
  .filter(documentationConfiguration(restDocumentation))
  .baseUrl("https://api.my-domain.com/")
  .build()

对于我来说,我使用服务的路径前缀-service/foo,因为我使用的是k8s入口,并且我的服务是在路径偏移量上提供的。

是否可以在不修改生产代码的情况下插入此类前缀?

相关文档片段:

https://docs.spring.io/spring-restdocs/docs/current/reference/html5/#configuration-uris-webtestclient

1 个答案:

答案 0 :(得分:2)

要记录另一个URI(而不是用来生成文档的URI),则必须编写自己的OperationPreprocessor。有一些预定义的内容,例如Preprocessors.modifyUris,但不允许修改请求路径。

检查以下webTestClient配置和URIUpdaterOperationRequest类。可以在GitHub上找到代码:https://github.com/Query-Interface/SO-Answers/blob/master/java/spring/rest-docs-modify-uripath/src/test/java/com/example/demo/DemoApplicationTests.java

public void init() throws Exception {
    final URIUpdaterPreprocessor preprocessor = new URIUpdaterPreprocessor();
    webTestClient = webTestClient.mutate()
        .filter((documentationConfiguration(this.restDocumentation)
                .operationPreprocessors()
                    .withRequestDefaults(preprocessor)
                    .withResponseDefaults(prettyPrint()))
                )
        .build();
}

private static final class URIUpdaterPreprocessor
    implements OperationPreprocessor {

    @Override
    public OperationRequest preprocess(OperationRequest request) {
        return new URIUpdaterOperationRequest(request);
    }

    @Override
    public OperationResponse preprocess(OperationResponse response) {
        return response;
    }

}

private static final class URIUpdaterOperationRequest
    implements OperationRequest {

    private OperationRequest delegate;

    public URIUpdaterOperationRequest(OperationRequest request) {
        delegate = request;
    }

    public byte[] getContent() {
        return delegate.getContent();
    }

    public String getContentAsString() {
        return delegate.getContentAsString();
    }

    public HttpHeaders getHeaders() {
        return delegate.getHeaders();
    }

    public HttpMethod getMethod() {
        return delegate.getMethod();
    }

    public Parameters getParameters() {
        return delegate.getParameters();
    }

    public Collection<OperationRequestPart> getParts() {
        return delegate.getParts();
    }

    public URI getUri() {
        URI sourceUri = delegate.getUri();
        UriComponentsBuilder builder = UriComponentsBuilder.fromUri(sourceUri);
        return builder
            .host(sourceUri.getHost())
            .replacePath("/service/foo"+sourceUri.getPath())
            .build().toUri();
    }

    public Collection<RequestCookie> getCookies() {
        return delegate.getCookies();
    }
}

我认为另一种可能性是更新胡子模板,以便在所有请求路径引用之前添加前缀。默认模板为located here on github