javalin-openapi icon indicating copy to clipboard operation
javalin-openapi copied to clipboard

Generate default documentation for registered routes

Open tipsy opened this issue 3 years ago • 1 comments

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.

tipsy avatar Oct 08 '22 12:10 tipsy

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);
    }

richardstephens avatar Dec 04 '22 17:12 richardstephens