简体   繁体   English

在 quarkus 应用程序中使用自定义 OASFilter 覆盖 smallrye microprofile 中的 ref 值

[英]Override ref value in smallrye microprofile using custom OASFilter in quarkus application

I'm trying to override ref value in schema for microprofile health check API in quarkus application.我正在尝试覆盖 quarkus 应用程序中 microprofile 运行状况检查 API 架构中的 ref 值。 I followed the below link Smallrye open api interceptor and created a custom filter which overrides OASFilter.我点击以下链接Smallrye 打开 api 拦截器并创建了一个覆盖 OASFilter 的自定义过滤器。 But, the ref value is not picking the new ref value from the filter.但是,ref 值并没有从过滤器中选择新的 ref 值。

@Override
public APIResponse filterAPIResponse(APIResponse apiResponse) {
    if (apiResponse.getRef()=="#/components/schemas/HealthCheckResponse")
    {
        String ref = "#components/schemas/microProfile";
        apiResponse.setRef(ref);
    }

    return apiResponse;
}

Basically, I need to add description to each property inside a schema.基本上,我需要为模式中的每个属性添加描述。

Existing schema:现有架构:

HealthCheckResponse:
  type: object
  properties:
    data:
      type: object
      nullable: true
    name:
      type: string
    status:
      $ref: '#/components/schemas/HealthCheckStatus'
HealthCheckStatus:
  enum:
  - DOWN
  - UP
  type: string

Expected schema change:预期的架构更改:

microProfile:
  description: microprofile response
  type: object
  properties:
    data:
      description: "Information of the service. If the service is down, this holds\
        \ the information of why it is failed."
      type: object
    name:
      description: 'Service Name '
      type: string
    status:
      description: 'Service Status '
      type: string

I added the property mp.openapi.filter= custom filter name in application.properties file.我在 application.properties 文件中添加了属性 mp.openapi.filter= custom filter name。 Any help is greatly appreciated.任何帮助是极大的赞赏。

There are 2 ways that I am aware off:我知道有两种方式:



You can programmatically create your own custom schema and reference it.您可以以编程方式创建自己的自定义模式并引用它。

In this case, the Schema is created programmatically, and does not have to exist anywhere in your openapi.yaml file.在这种情况下,架构以编程方式创建,并且不必存在于 openapi.yaml 文件中的任何位置。

    void updateHealthStatusRefWithProgrammaticSchema(OpenAPI openAPI) {

        openAPI.getPaths().getPathItems().forEach((String pathName, PathItem pathItem) -> {
            if (pathName.equalsIgnoreCase("/health-check")) {

                Schema dynamicSchema = OASFactory.createSchema().title("Programmatic-MicroProfile").description("dynamic-schema-description").type(Schema.SchemaType.OBJECT).properties(Map.of("custom-field-data", OASFactory.createSchema().description("Information of the service. If the service is down, this holds the information of why it is failed.").type(Schema.SchemaType.OBJECT)));
                openAPI.getComponents().addSchema("Dynamic-MicroProfile", dynamicSchema);

                pathItem.getGET().getResponses().getAPIResponse("200").getContent().getMediaType("application/json").setSchema(dynamicSchema);
            }
        });
    }

在此处输入图像描述



You can have a defined Static Schema in your openapi.yaml which you can reference programmatically.您可以在 openapi.yaml 中定义一个 Static 架构,您可以通过编程方式引用它。

In this case, the schema must exist in your openapi.yaml file, as you can see we are searching for it by doing get() **在这种情况下,模式必须存在于您的 openapi.yaml 文件中,正如您所看到的,我们正在通过执行get()来搜索它**

    void updateHealthStatusRefByUsingStaticSchema(OpenAPI openAPI) {

        openAPI.getPaths().getPathItems().forEach((String pathName, PathItem pathItem) -> {
            if (pathName.equalsIgnoreCase("/health-check")) {
                Schema staticMicroProfileSchema = openAPI.getComponents().getSchemas().get("Static-MicroProfile");
                pathItem.getGET().getResponses().getAPIResponse("200").getContent().getMediaType(MediaType.APPLICATION_JSON).setSchema(staticMicroProfileSchema);
            }
        });
    }

在此处输入图像描述



You update the openapi.yaml only if you want to have a Static Schema already defined.仅当您希望已定义 Static 架构时,才更新 openapi.yaml。

openapi.yaml openapi.yaml

components:
  schemas:
      HealthCheckResponse:
        type: object
        properties:
          data:
            type: object
            nullable: true
          name:
            type: string
          status:
            $ref: '#/components/schemas/HealthCheckStatus'
      HealthCheckStatus:
        enum:
          - DOWN
          - UP
        type: string
      Static-MicroProfile:
        description: microprofile response
        type: object
        properties:
          data:
            description: "Information of the service. If the service is down, this holds\
              \ the information of why it is failed."
            type: object
          name:
            description: 'Service Name '
            type: string
          status:
            description: 'Service Status '
            type: string

在此处输入图像描述


Filter:筛选:

package org.acme;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.eclipse.microprofile.openapi.OASFactory;
import org.eclipse.microprofile.openapi.OASFilter;
import org.eclipse.microprofile.openapi.models.Components;
import org.eclipse.microprofile.openapi.models.OpenAPI;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.eclipse.microprofile.openapi.models.PathItem;
import org.eclipse.microprofile.openapi.models.examples.Example;

import io.quarkus.logging.Log;
import org.eclipse.microprofile.openapi.models.media.Schema;

import javax.ws.rs.core.MediaType;

public class CustomOASFilter implements OASFilter {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void filterOpenAPI(OpenAPI openAPI) {

        //openApi.getComponents() will result in NULL as we don't have any openapi.yaml file.
        Components defaultComponents = OASFactory.createComponents();
        if (openAPI.getComponents() == null) {
            openAPI.setComponents(defaultComponents);
        }

        generateExamples().forEach(openAPI.getComponents()::addExample);

        updateHealthStatusRefWithProgrammaticSchema(openAPI);
    }

    Map<String, Example> generateExamples() {

        Map<String, Example> examples = new LinkedHashMap<>();

        try {

            ClassLoader loader = Thread.currentThread().getContextClassLoader();

            String userJSON = new String(loader.getResourceAsStream("user.json").readAllBytes(), StandardCharsets.UTF_8);
            String customerJson = new String(loader.getResourceAsStream("customer.json").readAllBytes(), StandardCharsets.UTF_8);

            Example userExample = OASFactory.createExample().description("User JSON Example Description").value(objectMapper.readValue(userJSON, ObjectNode.class));

            Example customerExample = OASFactory.createExample().description("Customer JSON Example Description").value(objectMapper.readValue(customerJson, ObjectNode.class));

            examples.put("userExample", userExample);
            examples.put("customerExample", customerExample);

        } catch (IOException ioException) {
            Log.error(ioException);
        }
        return examples;
    }

        void updateHealthStatusRefWithProgrammaticSchema(OpenAPI openAPI) {

            openAPI.getPaths().getPathItems().forEach((String pathName, PathItem pathItem) -> {
                if (pathName.equalsIgnoreCase("/health-check")) {

                    Schema dynamicSchema = OASFactory.createSchema().title("Programmatic-MicroProfile").description("dynamic-schema-description").type(Schema.SchemaType.OBJECT).properties(Map.of("custom-field-data", OASFactory.createSchema().description("Information of the service. If the service is down, this holds the information of why it is failed.").type(Schema.SchemaType.OBJECT)));
                    openAPI.getComponents().addSchema("Dynamic-MicroProfile", dynamicSchema);

                    pathItem.getGET().getResponses().getAPIResponse("200").getContent().getMediaType("application/json").setSchema(dynamicSchema);
                }
            });
        }

        void updateHealthStatusRefByUsingStaticSchema(OpenAPI openAPI) {

            openAPI.getPaths().getPathItems().forEach((String pathName, PathItem pathItem) -> {
                if (pathName.equalsIgnoreCase("/health-check")) {
                    Schema staticMicroProfileSchema = openAPI.getComponents().getSchemas().get("Static-MicroProfile");
                    pathItem.getGET().getResponses().getAPIResponse("200").getContent().getMediaType(MediaType.APPLICATION_JSON).setSchema(staticMicroProfileSchema);
                }
            });
        }
}

application.properties:应用程序.properties:

mp.openapi.filter=org.acme.CustomOASFilter

Full-Example:完整示例:

https://github.com/smustafa/quarkuks-openapi-exampleobject-loading-external-files https://github.com/smustafa/quarkuks-openapi-exampleobject-loading-external-files

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在自定义 OASFilter 处理期间,Microprofile 配置注入是 null,并且 microprofile-config.propetries 不被视为配置源 - Microprofile Config injection is null during custom OASFilter processing and microprofile-config.propetries is not considered as config source 为什么在使用 quarkus-amazon-lambda 和 quarkus-smallrye-openapi 包时会出现错误? - Why do I get an error when using quarkus-amazon-lambda and quarkus-smallrye-openapi packages? Quarkus - swagger-ui - smallrye 配置 - Quarkus - swagger-ui - smallrye configuration quarkus-smallrye-openapi - 无法解析引用:无法解析指针:/components/schemas - quarkus-smallrye-openapi - Could not resolve reference: Could not resolve pointer: /components/schemas Microprofile4/OpenApi3,如何定义示例请求值? - Microprofile4/OpenApi3, how to define example request value? 使用 Quarkus 的反应式 REST 服务的 OpenAPI 规范 - OpenAPI spec for reactive REST service using Quarkus Smallrye开api拦截器 - Smallrye open api interceptor Quarkus 应用程序 - 向 OpenAPI 定义添加基本路径 - Quarkus application - add base path to OpenAPI definition 将 smallrye-open-api 与 Wildfly 20 和部署到同一服务器的多个战争文件一起使用 - Using smallrye-open-api with Wildfly 20 and multiple war files deployed to same server 使用 Quarkus 时如何在 OpenAPI 中指定服务器 url 和描述? - How to specify server url and description in OpenAPI when using Quarkus?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM