【问题标题】:Adding path to base url in Spring Rest Docs?在 Spring Rest Docs 中添加基本 url 的路径?
【发布时间】:2018-12-24 21:30:40
【问题描述】:
【问题讨论】:
标签:
kotlin
spring-webflux
spring-restdocs
【解决方案1】:
要记录另一个 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();
}
}
我认为另一种可能性是更新 mustache 模板,以便在所有请求路径引用之前添加前缀。默认模板为located here on github。