Добавление пути к базовому URL-адресу в Spring Rest Docs?

У меня есть следующая конфигурация для использования с 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


person pixel    schedule 24.12.2018    source источник


Ответы (1)


Чтобы задокументировать другой 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();
    }
}

Я думаю, что еще одна возможность - обновить шаблоны усов, чтобы добавить префикс перед всеми ссылками на пути запроса. Шаблоны по умолчанию: находится здесь, на github.

person Arnaud Develay    schedule 28.12.2018