wcandillon / swagger-js-codegen

A Swagger Codegen for typescript, nodejs & angularjs
Apache License 2.0
693 stars 286 forks source link

parse definitions from Swagger #133

Open eburi opened 8 years ago

eburi commented 8 years ago

Added simple code to also parse the definitions found in swagger-files.

Sample template to output nothing but the definitions:

{{#definitions}}
interface {{name}} {{>type}}
{{/definitions}}
        var swaggerJson = JSON.parse(response);
        var typeTemplate = fs.readFileSync(__dirname + '/templates/typescript-definitions-only.mustache', 'utf-8');
        var opts = {
            swagger: swaggerJson,
            template: {
                class: typeTemplate
            }
        };
        var tsDefinitions = CodeGen.getTypescriptCode(opts);
        var defFile = fs.createWriteStream('./myDefinitions.d.ts');
        defFile.write(tsDefinitions);

The change in lib/typescript.js is for a special case I encountered with a swagger file where a parameter was defined as an array but misses the items-property describing the elements of the array. So I added this line to sanitize the input and default to a safe option instead of crashing when it tries to call 'hasOwnProperty' of undefined.

wcandillon commented 8 years ago

@eburi Can you provide some tests/examples?

no-more commented 8 years ago

Please merge this feature.

Thanks a lot.

wcandillon commented 8 years ago

@no-more @eburi Could you provide me an example on how to use this feature?

no-more commented 8 years ago

I haven't personally used it. I've just started a project and I faced this need. I think he provided some explanation on how to use this in this post #115

greuze commented 8 years ago

I am facing the same problem, my swagger spec have several type definitions, that are not generated, and as they are passed as parameters, there are compilation errors.

This pull request solves this problem (the types are generated), but there is a new minor problem. Types that are directly a string, are translated to an incorrect interface (other types are translated correctly):

interface user_id string

This causes a compilation error.

greuze commented 8 years ago

To try the code out, a template with definitions block must be specified:

{{#definitions}}
interface {{name}} {{>type}}
{{/definitions}}

I copied templates/typescript-class.mustache and put the block after the import * as request from "superagent"; (line 5). Specifying method template and type template is not required, as they will use default template. For example:

var opts = {
    swagger: swaggerJson,
    template: {
        class: typeTemplate
    }
};
var tsSourceCode = CodeGen.getTypescriptCode(opts);

With current code, the definition block is however not generated, but with pull request code, it is.