Search code examples
swaggerswagger-uiswagger-2.0swagger-editorswagger-codegen

How to access swagger yaml defined objects from javascript


I used Swagger Yaml to describe an endpoint and generate the mock server. The existing endpoint (that I'm mocking) doesn't follow RESTful principles 100%, so I simply want to overwrite the response that is returned by the mock server. The simple server code is shown below:

var swagger         = require('swagger-server');
var server          = swagger('map-cache.yaml');

var port            = 7072;

server.post('/map-qa_trunk/v2/getData', function(req, res, next) {
    var foo = { 
        err : 123,
        msg : "error message"
    };  
    res.json(foo);
});

server.listen(port, function() {
  console.log('Map Cache Mock Server is now running at http://localhost:' + port);
});

In the Yaml definition, there is an object defined called MapResponseData, how do I create an instance of this object so that I can populate it as needed and return in the res.json()? Something similar to below:

var response = getMapResponseData(); // don't know what this call should be
response.fieldA = 123;
res.json(response);

I am guessing this should be possible, since Swagger parsed the YAML file and is aware of all definitions that were specified.


Solution

  • Try outputting the request object to console.log to see if you can find reference to the swagger definition. Another option would be to pull the parsed swagger definition from the yaml file (using js-yaml for example) and extracting from there.

    However, my best advice is to use swagger-tools instead of swagger-server. The swagger-server package is alpha version and has fewer downloads, revisions, and users than swagger-tools. Benefit of swagger-tools is that it will be actively maintained and there is a larger community that can support you. To convert your project to swagger-tools, use swagger.io > Swagger Editor > Online Editor > Paste yaml in left pane > Generate Server > Node.js

    In swagger-tools the entire Swagger Yaml definition is contained in each request object:

    req.swagger.swaggerObject
    

    and you can pull the response object definitions from that as needed.