Giter Club home page Giter Club logo

Comments (7)

sichvoge avatar sichvoge commented on June 14, 2024

Can you paste the code you have?

from raml-js-parser-2.

domarmstrong avatar domarmstrong commented on June 14, 2024
import raml from 'raml-js-parser';
import path from 'path';
import { Router } from 'express';
let router = new Router();

/**
 * Parses docs/api.raml to generate routes
 * Route handlers are taken from (handlers) annotations
 */

const OVERRIDE = 10;

let api_file_path = path.join(process.cwd(), '/docs/api.raml');
let api = raml.loadApi(api_file_path).getOrThrow();

/**
 * Handle parser errors
 */
api.errors().filter(error => {
    // Ignore overrides
    if (error.code == OVERRIDE) return;

    throw error;
});

function processResource (api) {
    api.resources().forEach(res => {
        processMethods(res.completeRelativeUri(), res.allUriParameters(), res.methods());

        // Recursive call this function for all subresources
        processResource(res);
    });
}

function processMethods (path, params, methods) {
    methods.forEach(method => {
        console.log(method.method());
        console.log(method.annotations())
    })
}

from raml-js-parser-2.

sichvoge avatar sichvoge commented on June 14, 2024

And the full output?

from raml-js-parser-2.

domarmstrong avatar domarmstrong commented on June 14, 2024

Sorry I've kind of moved away to parsing the json tree instead. method get has an array of annotationRefImpl and given an annotationRefImlp, how do you get its properties etc.

But the gist was resources().methods().get.annotations()

[ AnnotationRefImpl {
    attr: 
     ASTPropImpl {
       _node: [Object],
       _parent: [Object],
       _implicit: false,
       values: {},
       _def: [Object],
       _prop: [Object],
       fromKey: false } } ] 

from raml-js-parser-2.

ddenisenko avatar ddenisenko commented on June 14, 2024

Hi @domarmstrong

To analyze annotations you'll have to jump from top-level API to high-level API. But is not all that scary, let me show you a couple of samples.

For the RAML code above, lets print all resources, methods and annotations of those methods:

api.allResources().forEach(function(resource){

    console.log("Resource: " + resource.absoluteUri())

    resource.methods().forEach(function(method){

        console.log("\tMethod: " + method.method())

        method.annotations().forEach(function(annotation){

            console.log("\t\tAnnotation:")

            var annotationAttributes = annotation.value().toHighlevel().attrs();

            annotationAttributes.forEach(function(attribute){

                console.log("\t\t\t" + attribute.name() + " : " + attribute.value())
            })
        })
    })
})

The output is:

Resource: /clients
    Method: get
        Annotation:
            name : (handler)
            value : routes.resources.clients.list

Now lets see what happens if annotation has two attributes and RAML looks like this:

#%RAML 1.0
title: Test

annotationTypes:
  handler:
    parameters:
      first: string
      second: string

/clients:
  get:
    (handler):
      first: routes.resources.clients.list
      second: test

The output of the same JS will be following:

Resource: /clients
    Method: get
        Annotation:
            name : (handler)
            first : routes.resources.clients.list
            second : test

But what if annotation has a parameter of a custom user-defined type? It becomes more complicated, but not too much.

RAML is the following:

#%RAML 1.0
title: Test

types:
  TestType:
    properties:
      firstField: string
      secondField: string

annotationTypes:
  handler:
    parameters:
      first: string
      second: TestType

/clients:
  get:
    (handler):
      first: routes.resources.clients.list
      second:
        firstField: firstFieldValue
        secondField: secondFieldValue

Lets refactor our JS code to print all the children of the high-level node recursively, and then use this method to annotation's high-level counterpart:

function printHighLevelNode(node, indent) {
    var nodeDefinitionName = node.definition().nameId()
    var parentPropertyPointingToNode = node.property().nameId()

    console.log(indent + parentPropertyPointingToNode + " [" + nodeDefinitionName + "]")
    var attributes = node.attrs();

    attributes.forEach(function(attribute){

        console.log(indent + "\t" + attribute.name() + " : " + attribute.value())
    })

    var elements = node.elements();

    elements.forEach(function(element){
        printHighLevelNode(element, indent + "\t")
    })
}

api.allResources().forEach(function(resource){

    console.log("Resource: " + resource.absoluteUri())

    resource.methods().forEach(function(method){

        console.log("\tMethod: " + method.method())

        method.annotations().forEach(function(annotation){

            printHighLevelNode(annotation.value().toHighlevel(), "\t\t")
        })
    })
})

The output is the following:

Resource: /clients
    Method: get
        annotations [handler]
            name : (handler)
            first : routes.resources.clients.list
            second [TestType]
                firstField : firstFieldValue
                secondField : secondFieldValue

node.definition().nameId() returns the name of the definition of the node. In other words, it is the name of the thing, that can be typed here. So for your annotation it is handler, and for second annotation argument it is TestType.

node.property().nameId() returns the name of the parent property, which points to this node. In this case it is annotations for handler annotation, and second for TestType instance.

Let me know if you have questions.

from raml-js-parser-2.

ddenisenko avatar ddenisenko commented on June 14, 2024

Changed the sample above to provide a bit more info regarding the high-level.

from raml-js-parser-2.

domarmstrong avatar domarmstrong commented on June 14, 2024

Thanks, this is exactly what I needed

from raml-js-parser-2.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.