简体   繁体   中英

Iterating over Swagger YAML File to dynamically generate a list of properties

I am trying to create a script that can accept a swagger yml file (like the example petstore.yaml), and generate a list of used "attributes" from the file.

This involves the parsing of yaml, then iterating over all elements in the json object to return the required data. I intend to traverse all the paths to identify valid responses, but for now I just want to filter out all definitions specified in the yaml file, then for each def, output the list of properties.

a sample yaml file can be downloaded here

at the end of the day, i would like to generate a string for each attribute which shows something like

<filename>~Pet~id~integer~int64
<filename>~Pet~name~string~
<filename>~Pet~tag~string~

for this, i need to locate the 'definitions' node, and iterate over all sub-nodes to read the info.

I am struggling to get the logic right for a yaml styled file.. Below is my working code.

It just feels to me like I have over-complicated the iterative looping (maybe a better solution would be to use regex?

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <title>Read YAML</title>
        </script><script src='https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.min.js'>            
    </script>
    <body>
        <input type="file" id="file-input" />
        <h3>Contents of the file:</h3>
        <pre id="file-content"></pre>
        <div id='output'></div>
    </body>
    <script>
        var yaml = window.jsyaml;
        </script>
    <script src="app.js"></script>
</html>

my javascript file

var body = '';
var mystring = '' 
function readSingleFile(e) {
    var file = e.target.files[0];
    if (!file) {
      return;
    }
    var reader = new FileReader();
    reader.onload = function(e) {
      var contents = e.target.result;
      displayContents(contents);
    };
    reader.readAsText(file);
}

function displayContents(contents) {
      var element = document.getElementById('file-content');
      var doc = yaml.load(contents);
      // Process the file.
      // Process only the definitions section of the file
      var definition = doc.definitions
      console.log (definition) ;
      for(var def in definition) {
        if(definition.hasOwnProperty(def)) {
          var node = definition[def]
            if (typeof(node) === 'object') {
                // loop through the definitions
                processContents(node)
            }
        }
      }

      function processContents(obj) {
        for (var item in obj) {
              var definitions = obj[item]
              if (typeof definitions === 'object'){
                for (var attribute in definitions) {
                  // HELP -- if there is an attribute called "properties"  then iterate over all properties and create the concatenated string
                  // Broken from here !!!!
                  if (attribute.properties) {
                      for (var param  in attribute.properties) {
                        mystring = param.name + '~' + param.type + '~' + param.description + '~' + param.format
                      }
                  }
              }
              }
        }

      }
      document.getElementById('output').innerHTML = body;
 }

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);

I am running out of time so I will leave it here. It's not as refined as it is but I hope it helps you.

So I did a recursive function to iterate through the objects. The function takes in an object and a prefix. The prefix will be used for printing the details. The exclude prefixes is used to not show certain field names and the exclude types is to not print certain types. Loop through the fields of an object an catch format, type, description and whatever you want to catch. When done looping the fields of an object check if the type field is populated. If it is then log the parameter details.

var body = '';
var mystring = '' 
function readSingleFile(e) {
    var file = e.target.files[0];
    if (!file) {
      return;
    }
    var reader = new FileReader();
    reader.onload = function(e) {
      var contents = e.target.result;
      displayContents(contents);
    };
    reader.readAsText(file);
}

function displayContents(contents) {
      console.log('---contents---')
      console.log(contents)
      var element = document.getElementById('file-content');
      console.log('---element----')
      console.log(element)
      var doc = yaml.load(contents);
      console.log('---doc')
      console.log(doc)
      // Process the file.
      // Process only the definitions section of the file
      var definition = doc.definitions
      console.log('---definition---')
      console.log (definition) ;

    processContents2(doc.definitions)

    function processContents2(obj, prefix) {
        const excludePrefixes = ['properties']
        const excludeTypes = ['object', 'array']
        let format = ''
        let type = ''
        let description = ''
        let count = 0;
        for (var field in obj) {
            if (typeof obj[field] === 'object') {
                processContents2(obj[field], (prefix || '') + (excludePrefixes.indexOf(field) === -1 ? '~' + field : ''))
            } else {
                if (field === 'format') {
                    format = obj[field]
                } else if (field === 'type') {
                    type = obj[field]
                } else if (field === 'description') {
                    description = obj[field]
                }
            }
        }
        if (type && (excludeTypes.indexOf(type) === -1)) {
            console.log((prefix || '') + '~' + type  + (description ? '~' + description : '') + (format ? '~' + format : ''))
        } 
      }

      document.getElementById('output').innerHTML = body;
 }

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM