Giter VIP home page Giter VIP logo

swagger-node-codegen's Introduction

THIS PACKAGE IS NOT MAINTAINED ANYMORE. IF YOU WANT TO MAINTAIN IT DROP ME A LINE AT fran.mendez[at]hey.com.

OpenAPI Node.js
Code Generator



Use your API OpenAPI 3.x/Swagger 2 definition to generate Node.js ES7-compliant code for your API.

The generated code features:

  • ES7
  • ESLint
  • YAML config file
  • Express
  • No transpiling

Install

To use it from the CLI:

npm install -g swagger-node-codegen

To use it as a module in your project:

npm install --save swagger-node-codegen

Requirements

  • Node.js v7.6+

Usage

From the command-line interface (CLI)

  Usage: snc [options] <swaggerFile>


  Options:

    -V, --version                  output the version number
    -o, --output <outputDir>       directory where to put the generated files (defaults to current directory)
    -t, --templates <templateDir>  directory where templates are located (defaults to internal nodejs templates)
    -h, --help                     output usage information

Examples

The shortest possible syntax:

snc swagger.yaml

Specify where to put the generated code:

snc swagger.yaml -o ./my-api

As a module in your project

const path = require('path');
const codegen = require('swagger-node-codegen');
const swagger = require('./swagger.json');

codegen.generate({
  swagger,
  target_dir: path.resolve(__dirname, './my-api')
}).then(() => {
  console.log('Done!');
}).catch(err => {
  console.error(`Something went wrong: ${err.message}`);
});

The swagger parameter can be either JSON or a path pointing to a JSON or YAML file.

const path = require('path');
const codegen = require('swagger-node-codegen');

codegen.generate({
  swagger: path.resolve(__dirname, './swagger.yml'),
  target_dir: path.resolve(__dirname, './my-api')
}).then(() => {
  console.log('Done!');
}).catch(err => {
  console.error(`Something went wrong: ${err.message}`);
});

Using async/await

The function codegen.generate returns a Promise, so it means you can use async/await:

const path = require('path');
const codegen = require('swagger-node-codegen');

try {
  await codegen.generate({
    swagger: path.resolve(__dirname, './swagger.yml'),
    target_dir: path.resolve(__dirname, './my-api')
  });
  console.log('Done!');
} catch (err) {
  console.error(`Something went wrong: ${err.message}`);
}

API Documentation

Modules

codegen

This module generates a code skeleton for an API using OpenAPI/Swagger.

generatePromise

Generates a code skeleton for an API given an OpenAPI/Swagger file.

codegen

This module generates a code skeleton for an API using OpenAPI/Swagger.

generate ⇒ Promise

Generates a code skeleton for an API given an OpenAPI/Swagger file.

Param Type Description
config Object Configuration options
config.swagger Object | String OpenAPI/Swagger JSON or a string pointing to an OpenAPI/Swagger file.
config.target_dir String Path to the directory where the files will be generated.
config.templates String Path to the directory where custom templates are (optional).

Templates

You can create your own templates.

Authors

swagger-node-codegen's People

Contributors

andy-viv avatar callmemagnus avatar david-shepard avatar fmvilas avatar guided1 avatar imsidj avatar khannarishir avatar kloener avatar richardklose avatar stnguyen90 avatar tswaters avatar vaelor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swagger-node-codegen's Issues

HEAD methods should be before GET methods

Hi, I used the codegen (and it works wonderful). An issue I detected is that the order of the methods should be re-arranged in order to get the HEAD method working (when there is a GET method with the same path).
Thank you!

Feat request: add ability to generate model files

In the same way we can generate multiple operation files from a single template, it would be beneficial to generate multiple model files from a single template. This would allow us to support strongly typed languages that share interfaces/models.

We'd just need a way to differentiate those types of files. Currently, operations are denoted by three underscores, maybe we could reserve some other set of characters for models. Another idea to solve for this would be to have some kind of file registry. This would allow us to associate a template explicitly with one of the many ways it can be interpreted by the codegen. This would also let us name handlebar files in .hbs so we can get some intellisense while templating locally.

I'd be happy to work on this :)

path template with hypen produces invalid json object in the routes file

OAS3 definition file snippet:
"/accessories/{accessory-id}/open": {
"description": "Represents the custom "Open" operation",
"post": {

Generates a const in a routes file that looks like this:
const options = {
languageCode: req.query.languageCode,
localAccessDesired: req.query.localAccessDesired,
inputOutputCallback: req.query.inputOutputCallback,
contentFilter: req.query.contentFilter,
accessory-id: req.params.accessory-id
};

accessory-id is invalid and needs to be surrounded with quotes.

I really like this tool and want to use it in my CI/CD setup.

Custom handlebar helpers

Hi,
I'd like to be able to create and include helper for handlebars not in the library. Do you have a preference of how you want to achieve this?

I was thinking of using a parameter supplying another parameter:

-b, --handlebars path to external handlebars helpers file

This would then include the file if the path is valid and it exists.

Thoughts?

I'll put in a pull request if you agree

Service template shouldn't advise the user to return an error object

It doesn't look like this works
https://github.com/fmvilas/swagger-node-codegen/blob/master/templates/express-server/src/api/services/___.js#L27-L30

 // throw new Error({
  //   status: 500, // Or another error code.
  //   error: 'Server Error' // Or another error message.
  // });

the caller of the function expects an Error object with fields status & error, but this doesn't do that since the Error constructor doesn't take an object - it expects a string https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error. You should be able to do

// throw {
  //   status: 500, // Or another error code.
  //   error: 'Server Error' // Or another error message.
  // };

Code Generation Not Working on Mac

Error Message

Done!
fs.js:50
    throw new TypeError('"options" must be a string or an object, got ' +
    ^

TypeError: "options" must be a string or an object, got number instead.
    at getOptions (fs.js:50:11)
    at Object.fs.writeFile (fs.js:1184:13)
    at /Users/lalluanthoor/node_modules/swagger-node-codegen/dist/codegen.js:127:18
    at tryToString (fs.js:425:3)
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:412:12)

I went into the source and removed , 0 from all the lines with _fs2.default.writeFile(target_file, content, 0, 'utf8', function (err) {. After that the code is generated properly. But when I say make build it fails with error:

...
Building API...
[08:21:19] Using gulpfile ~/swagger/gulpfile.js
[08:21:19] Starting 'build'...

events.js:160
      throw er; // Unhandled 'error' event
      ^
TypeError: /Users/lalluanthoor/swagger/src/api/routes/author.js: Duplicate declaration "err_response"
  37 |       const err_response = { status: 401, message: 'unauthorized' };
  38 |       return res.status(401).send(err_response);
> 39 |       const err_response = { status: 404, message: 'author not found' };
     |             ^
  40 |       return res.status(404).send(err_response);
  41 |       const err_response = { status: 500, message: 'internal server error' };
  42 |       return res.status(500).send(err_response);
    at File.buildCodeFrameError (/Users/lalluanthoor/swagger/node_modules/babel-core/lib/transformation/file/index.js:427:15)
    at Scope.checkBlockScopedCollisions (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/scope/index.js:398:27)
    at Scope.registerBinding (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/scope/index.js:592:16)
    at Scope.registerDeclaration (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/scope/index.js:496:14)
    at Object.BlockScoped (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/scope/index.js:244:28)
    at Object.newFn (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/visitors.js:318:17)
    at NodePath._call (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/path/context.js:44:14)
    at NodePath.visit (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/Users/lalluanthoor/swagger/node_modules/babel-traverse/lib/context.js:150:16)
make: *** [build] Error 1

Config

$ node --version
v7.0.0

$ npm --version
3.10.8

missing '/' when basePath is empty

The OpenApi 3 Spec does not require a basePath on top level in the definition so it might be empty. This of course means, that there is no / in the basePath and so it should be added before each generated route.
This can be reproduced by using the OpenAPI 3 petstore.yaml example.

Currently the Handlebars helper endsWith does not cover this scenario. It compares the basePath's length-1 (=-1) with a not found /(= -1) which then leads to the same behavior as if there was a / at the end of the basePath.

open api 3.x - requestBody not read, generates blank options

I fed the petstore-expanded.yaml file to this tool -

it works quite well, but one the endpoints, post /pet does not properly pull in the requestBody stanza, so the options passed into the service end up being blank, instead of passing along req.body

Here's what is generated by the current template:

/**
 * Create a pet
 */
router.post('/', async (req, res, next) => {
  const options = {
  };

  try {
    const result = await pets.createPets(options);
    res.status(result.status || 200).send(result.data);
  } catch (err) {
    return res.status(500).send({
      status: 500,
      error: 'Server Error'
    });
  }
});

openapi 3.0.0 Can not load the content of the Swagger specification file

Hi,
if i try to start cli command
snc .\swagger\swagger.yaml -o .\api
i get displayed follow Exception:

Can not load the content of the Swagger specification file
{ Error: ENOENT: no such file or directory, open 'C:...\swagger\swagger.yaml'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\...\swagger\swagger.yaml' }
Aaww �. Something went wrong:
TypeError: Cannot read property 'basePath' of undefined
at swagger2 (C:...\swagger-node-codegen\lib\swagger2.js:57:30)
at

here is servers definition in yaml

_servers:
url: http://localhost:10010/v1

No such a file or directory

Running snc for the first time, I always got the following error:
/usr/bin/env: ‘node --trace-deprecation’: No such file or directory

After banging my head on the wall for a couple of times, I realized the problem is the shebang on the main file. temporarily removing the flag fixed the issue for me, but that is not a real solution. What could be done?

Thanks in advance!

does not work with APIs versioning

Hi,

I found that this lib does not work with APIs versioning, e.g., my APIs may have

  • /api/v1/users
  • /api/v2/users

I would like to create 2 more folders, v1 and v2 under routes and services.
But It is impossible to do it for this version.

Issue on generation

I used the default swagger spec on http://editor.swagger.io/
When I run it
snc swagspec.yaml -o ./my-api
or
snc swagspec.yaml

But I get error
/usr/local/lib/node_modules/swagger-node-codegen/lib/codegen.js:138
walker.on('file', async (root, stats, next) => {
^

SyntaxError: Unexpected token (
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (/usr/local/lib/node_modules/swagger-node-codegen/cli.js:6:17)

Creating a new version

Is there a way to update the folder after specification edit or addition without deleting the entire server and rewriting the endpoint implementations?

Target dir can't handle relative paths properly

Running snc -t ./api-templates -o ./src/app/services/gen/ schema.yaml

Results in some files being moved to the output folder, but not all.
Update Only files that do not begin with ___ are moved to the correct folder.

The rest is put into the template folder.

My folder structure:

./api-templates/___.service.ts
./api-templates/api.module.ts
# generate to:
./src/app/services/gen/

Edit: The below was not correct! See my other comment

Location of the issue seems to be

target_dir: program.output,
  templates: program.templates ? path.resolve(process.cwd(), program.templates) : undefined

Where templates: uses path.resolve, target_dir: does not.

feature request: rename hbs to js

So, my IDE really doesn't like it when I look at these template js files - it whines and complains about syntax errors and it's really hard to see where real problems are.

I can rename the files to .hbs and the IDE is much happier, and I get near things like syntax highlighting and the like

But now when I run generate, it generates a bunch of hbs files which I need to either rename afterwards or configure my loader to recognize hbs as js - but only in the output directory.

It would be really great if this use case "just worked" -- i.e., if we see hbs files in source, just rename to .js in the output (it's probably what the user wanted). Of course, this doesn't work for other file formats, like TS -- so maybe a configuration option can be provided to overwrite this behavior

fs Error - node v8.91

Hi, while using the generator under node v8.91, the following error is thrown

fs.js:75
throw new TypeError('"options" must be a string or an object, got ' +
^

TypeError: "options" must be a string or an object, got number instead.
at getOptions (fs.js:75:11)
at Object.fs.writeFile (fs.js:1261:13)
at C:/Users/RK/Documents/github/org/swagger-node-codegen/dist/codegen.js:127:18
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)

This piece of code causing this is
fs.writeFile(target_file, content, 0, 'utf8', (err) => { if (err) throw err; });
at lines 47, 79 & 100 of lib/codegen.js
https://github.com/fmvilas/swagger-node-codegen/blob/master/lib/codegen.js

This was not an issue in node v6.x because passing 0 triggered the default options

https://github.com/nodejs/node/blob/v6.x/lib/fs.js
line 1306 node v6.x lib/fs.js
fs.writeFile = function(path, data, options, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); if (!options || typeof options === 'function') { options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; } else if (typeof options === 'string') { options = { encoding: options, mode: 0o666, flag: 'w' }; } else if (typeof options !== 'object') { throwOptionsError(options); }

This behaviour was updated in v8.x and the error being thrown is from the getOptions function from the node library v8.x

This was reported earlier #4 and as per the suggestion provided there removing 0 from the piece of code fixes this issue however those changes were not made part of the pull request.

Pass the whole swagger/openapi spec into the operation files

I currently have a case where it would make my life easier if I had access to other parts of the swagger spec (like components) in an operation file (___.js).
The only context I have there is 'operation'.

Do you think it makes sense to include that there? (if I happen to have the time for it, I could also implement it)

I would assume https://github.com/fmvilas/swagger-node-codegen/blob/master/lib/codegen.js#L76 would be a place to start (next to operation also provide the whole openapi object, so existing implementations wouldn't break ofc)

Error on update of openapi spec

When I update my openapi.json (or yml) with for example an extra endpoint the codegen fails on existing files.

In my opinion the library has to overwrite existing files and has to ignore files according to an ignore file.

The library now simply fails with an error:

Aaww 💩. Something went wrong:
Error: File /app/.editorconfig exists.
    at copyHelper (/app/node_modules/fs.extra/fs.copy.js:22:19)
    at FSReqWrap.oncomplete (fs.js:153:5)

Getting an exception on Mac

I tried with a sample over here but it is always giving an exception.

May I know what could be the issue?

Node : v6.13.1

/usr/local/lib/node_modules/swagger-node-codegen/lib/codegen.js:138
    walker.on('file', async (root, stats, next) => {
                            ^

SyntaxError: Unexpected token (
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/local/lib/node_modules/swagger-node-codegen/cli.js:6:17)

Thanks,
Ayyappa

No routes nor services are generated

The server is properly generated saying "Done" without errors.

However no files are generated under src/api/routes and src/api/services.
Which lead to this error:

Error: Cannot find module './routes/server-settings'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (C:\Users\SESA351036\Documents\Dev\schneider\edm\test\my-api\src\api\index.js:17:29)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)


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.