javalin / javalin-openapi

Annotation processor for compile-time OpenAPI & JsonSchema, with out-of-the-box support for Javalin 5.x, Swagger & ReDoc
https://github.com/javalin/javalin-openapi/wiki
Apache License 2.0
45 stars 17 forks source link

Generate default documentation for registered routes #49

Open tipsy opened 1 year ago

tipsy commented 1 year ago

The old plugin had support for default responses:

    OpenApiOptions().apply {
        defaultDocumentation { doc ->
            doc.json("500", ErrorResponse::class.java)
            doc.json("503", ErrorResponse::class.java)
        }
    }

These are responses which could occur on any endpoint.

richardstephens commented 1 year ago

I got this working in a rather hack-ish way by supplying a custom document processer.

        options.setDocumentProcessor(
                (ObjectNode document) -> {
                    document.get("paths")
                            .forEach(
                                    pathNode ->
                                            pathNode.forEach(
                                                    methodNode ->
                                                            mutateResponseNode(
                                                                    methodNode.get("responses"))));
                    return document.toPrettyString();
                });
    private static ObjectNode childNode(String key, ObjectNode child) {
        ObjectNode object = objectMapper.createObjectNode();
        object.set(key, child);
        return object;
    }

    private static void mutateResponseNode(JsonNode node) {
        ObjectNode mutableNode = (ObjectNode) node;
        ObjectNode schemaNode = objectMapper.createObjectNode();
        schemaNode.put("$ref", "#/components/schemas/ErrorResponse");
        ObjectNode error500 = childNode(
                        "content", childNode("application/json", childNode("schema", schemaNode)));
        error500.put("description", "Server error");
        ObjectNode error503 = childNode(
                        "content", childNode("application/json", childNode("schema", schemaNode)));
        error503.put("description", "Service unavailable");

        mutableNode.putIfAbsent("500", error500);
        mutableNode.putIfAbsent("503", error503);
    }