Coder Social home page Coder Social logo

mermade / openapi-codegen Goto Github PK

View Code? Open in Web Editor NEW
291.0 12.0 47.0 3.4 MB

OpenAPI 3.0 CodeGen plus Node.js minus the Java and emojis

Home Page: https://mermade.github.io/openapi-codegen

License: Apache License 2.0

JavaScript 42.63% Shell 16.93% Dockerfile 0.16% Scala 2.06% Apex 10.72% HTML 1.93% ActionScript 8.46% PHP 5.11% PowerShell 0.47% Ruby 9.54% Rust 0.07% CSS 1.92%
openapi openapi3 swagger api documentation code-gene code- nodejs javascript python

openapi-codegen's People

Contributors

agnat avatar andrefilimono avatar andrewsomething avatar b3nab avatar dependabot-preview[bot] avatar dependabot[bot] avatar greenkeeper[bot] avatar iilyak avatar jaredpalmer avatar jhannes avatar mikeralphson avatar pieterlexis avatar steveej avatar tm1000 avatar wingedfox avatar zewish 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  avatar  avatar  avatar  avatar

openapi-codegen's Issues

Error: Cannot find module '<currentpath>\configs\htmlDocs2.json

I installed the package via npm and called it with
cg htmlDocs2 docs/openapi.yaml

But it fails to load the config file because it's looking relative to the current path instead of relative to the cg.js file (the require in cg.js:54)

How is this supposed to work?

I assume this is because the path.resolve in line 53 resolves ./ as cwd and not __dirname. While the require would treat them as equal.

It would probably work just fine without the path.resolve. (just path.join, but then ofc paths relative to cwd would not work anymore...)

node cg adds always json extension to file

Hi,

I cloned the master git branch and tried to execute node cg nodejs defs/swagger.yaml
But cg appends always .json to the input file and executes node cg nodejs defs/swagger.yaml.json
I renamed the file to swagger.yaml.json and executed the first command again and cg was able to find the file but I got an error with unexpected token, which is comprehensible because the file is yaml and not json.

OpenAPI 3.0.0 petstore.yaml definition is not supported

  • node --version: v6.12.2
  • openapi-codegen at fda84f8

The command run is cg --debug --lint --verbose nodejs defs/petstore.yaml for the following reports.

Null response leads to TypeError

https://github.com/OAI/OpenAPI-Specification/blob/e9c539d86f080f133aa35c3e7db33ef004496625/examples/v3.0/petstore.yaml#L47-L49

leads to

{ level: 'Error',
  elementType: 'Context',
  elementId: '#/info/license',
  message: 'expected Object { name: \'MIT\' } to have property url' }
/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/adaptor.js:326
            let contentType = Object.values(response.content)[0];
                                     ^

TypeError: Object.values is not a function
    at convertOperation (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/adaptor.js:326:38)
    at convertToApis (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/adaptor.js:448:33)
    at Object.transform (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/adaptor.js:786:24)
    at Object.main (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/index.js:30:13)
    at main (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/cg.js:155:19)
    at Object.<anonymous> (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/cg.js:197:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)

Adding some content helps to workaround this issue.

@@ -47,6 +47,7 @@ paths:
       responses:
         201:
           description: Null response
+          content: Null content
         default:
           description: unexpected error
           content:

$ref usage leads to TypeError

/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:59
  var ref = obj.$ref;
               ^

TypeError: Cannot read property '$ref' of undefined
    at resolveReference (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:59:16)
    at convertResponses (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:188:24)
    at convertOperations (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:93:17)
    at convert (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:25:3)
    at Object.transform (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/adaptor.js:680:23)
    at Object.main (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/index.js:30:13)
    at main (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/cg.js:155:19)
    at Object.<anonymous> (/home/steveej/.npm-packages/lib/node_modules/openapi-codegen/cg.js:197:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)

Being unfamiliar with the project and JS, this is where I'm stuck.

nodejs server OpenAPI 3.0 links

First of all, thanks a lot for making a code generator compatible for OpenAPI 3.0.x and nodejs-server.

I noticed that (at least in version 1.3.4) there are a couple features of OpenAPI that do not seem to be fully working, and I couldn't find any reference to this in your documentation.

Are you interested in implementing these features? Did you know that they were part of the OpenAPI 3.0.0 specification?

  1. Response links

OpenAPI 3.0.x allows for an additional 'links' property in the response, that is described in the above link. The failure I had was for the following (brief but complete) example:

openapi: 3.0.0
info:
  title: 'title'
  description: 'description'
  version: 0.0.1


servers:
- url: 'http://localhost:5000/api/v0'
  description: 'Local dev server'


paths:
  /pets:
    get:
      operationId: 'getAllPets'
      summary: 'Get all pets'
      description: 'Retrieve the latest pets'
      responses:
        '200':
          description: 'Successful: list of pets'
          content:
            application/json:
              schema:
                type: 'object'
                properties:
                  pets:
                    type: 'array'
                    items:
                      type: 'object'
                      properties:
                        petId:
                          type: 'string'
          links:
            petId:
              operationId: 'getPetById'
              parameters:
                petId: '$response.body#/pets/petId'

  /pets/{petId}:
    get:
      operationId: 'getPetById'
      summary: 'Get a pet by its ID'
      parameters:
        - in: 'path'
          name: 'petId'
          schema:
            type: 'string'
          required: true
          description: 'ID of the pet to get'
      responses:
        '200':
          description: 'Success'
          content:
            application/json:
              schema:
                type: 'object'
                properties:
                  pet:
                    $ref: '#/components/schemas/Pet'

components:
  schemas:
    Pet:
      type: 'object'
      properties:
        name:
          type: 'string'
  1. Response Patterned Fields

Another (arguably simpler) feature that OpenAPI 3.0.0 introduced is the "Patterned Fields". They are used in order to provide a "catch all" nest for HTTP status codes.

For example, one could write:

paths:
  /pets:
    get:
      operationId: 'getAllPets'
      responses:
        '200':
          description: 'Success'
        '4XX':
          description: 'Other failure than 404'
        '404':
           description: 'Not found'

schema $refs to objects broken?

I have verified this in several templates: When I create a property of a schema object that is a $ref to another object in the same file, it sets the type of the property to IO.OpenAPI\Name

Also, when attempting to make an array of a some other type that is referenced, it just makes that type Array instead of Array<OtherType>. Also, if I set the OtherType to explicitly be of type object, and set the properties.. it just calls the other type object

When I am referencing enum types in the same way, it works.
Here's a repro case:

openapi: "3.0"
info:
  version: 0.0.2
  title: Sample User Schema
  license:
    name: Unlicensed
servers:
  - url: https://wat.huh
    description: Internal API
paths: {}
components:
  schemas:
    UserInitialState:
      required:
        - id
        - firstName
        - lastName
        - email
        - verified
      properties:
        id:
          type: string
        organizationIds:
          type: array
          items:
            $ref: "#/components/schemas/UserOrganization"
        verified:
          $ref: "#/components/schemas/VerifiedStatus"
    VerifiedStatus:
      required:
        - id
        - phone
        - email
      properties:
        id:
          type: boolean
        phone:
          type: boolean
        email:
          type: boolean
    UserOrganization:
      properties:
        id:
          type: string
        awesomenessLevel:
          $ref: "#/components/schemas/UserAwesomenessLevel"
    UserAwesomenessLevel:
      type: string
      enum:
        - LOW
        - MEDIUM
        - HIGH

And the resulting object rendered by typescript-fetch (similar results with typescript-axios and others as well.

export interface UserInitialState {
    /**
     *
     * @type {string}
     * @memberof UserInitialState
     */
    id: string;
    /**
     *
     * @type {Array}
     * @memberof UserInitialState
     */
    organizationIds?: Array;
    /**
     *
     * @type {IO.OpenAPI\VerifiedStatus}
     * @memberof UserInitialState
     */
    verified: IO.OpenAPI\VerifiedStatus;
}

Error in getReferenceSchema when namespace contains a dot character

When the namespace contains dots, there is the following error:
Internal Error: #/components/schemas/Api.v1.ClassName not found!
at getReferenceSchema (D:\Projects\JVM.BackOffice\node_modules@openapi-codegen\typescript\lib\core\getReferenceSchema.js:20:15)

This happens because of line 18 in getReferenceSchema, which uses dot as a special separator character:
const referenceSchema = (0, lodash_1.get)(openAPIDocument, refPath.join("."));

The fix is to use the other overload of get which can accept an array directly, like the following:
const referenceSchema = (0, lodash_1.get)(openAPIDocument, refPath);

Ability to call swagger-codegen / openapi-generator APIs directly

Based on the comments here:

We wanted to mention Mermadeโ€™s openapi-codegen
project too. Fundamentally it performs the same behaviors as OpenAPI Generator, but itโ€™s a simpler, much more minimal implementation written in Node.js. We quite like this project, but itโ€™s a distance behind OpenAPI Generator at the moment. It actually uses the same Mustache templates which are used in OpenAPI Generator, but with the behaviors for each language and framework written in JavaScript.

While the re-use of templates is great, it does mean that the templates embedded in this tool often fall out of sync with the versions in OpenAPI Generator, so you may find issues in templates which have already been fixed elsewhere.

Weโ€™ll be following along closely with this project to see how it develops in the hope that it provides us a simpler, more lightweight toolchain in the future.

it is frustrating that we haven't updated the templates recently, nor made a decision on whether to stick with the apparently unmaintained swagger-codegen v2.3 templates or move to following the (apparently very slowly progressing) swagger-codegen v3.x templates, or switch to the openapi-generator templates.

Questions

  • Would we need a (local) config file for each set of templates still? The current source templates don't include a declarative full-filename for the target of the mustache templates

Doesn't accept URL in $ref (downconverting to OAS 2.0)

For OpenAPI input that has $ref values that point to a URL, the cg process stops, e.g. when encounterint a line like:

$ref: http://localhost:8090/openapi-local/Message.v1_0_6.yaml

it stops with:

$ cg -v -d debug ../local-test/openapi-local/openapi.yaml
Loaded config debug
Loaded definition ../local-test/openapi-local/openapi.yaml
/usr/local/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:64
keys.forEach(k => cur = cur[k]);
^

TypeError: Cannot read property 'localhost:8090' of undefined
at keys.forEach.k (/usr/local/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:64:30)
at Array.forEach ()
at resolveReference (/usr/local/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:64:8)
at convertResponses (/usr/local/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:189:24)
at convertOperations (/usr/local/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:93:17)
at convert (/usr/local/lib/node_modules/openapi-codegen/lib/orange/downconvert.js:25:3)
at Object.transform (/usr/local/lib/node_modules/openapi-codegen/adaptor.js:694:23)
at Object.main (/usr/local/lib/node_modules/openapi-codegen/index.js:35:13)
at main (/usr/local/lib/node_modules/openapi-codegen/cg.js:174:19)
at Object. (/usr/local/lib/node_modules/openapi-codegen/cg.js:217:4)

nodejs template: kebab-case component schema name creates invalid JavaScript

e.g.

      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/foo-bar-baz'

The generate API files have code like this:

module.exports.do_foo = function do_foo (req, res, next) {
  var foo-bar-baz = req.swagger.params['foo-bar-baz'].value;
  // ...
}

- is not a valid identifier character in JavaScript, because it's used as a mathematic operator foo - bar - baz.

The identifier is also used in the generated impl/API service:

exports.do_foo = function(foo-bar-baz) {
  // ...
}

Use swagger-tools functionality

As we have swagger-tools along for the ride for the Node.js server (which will become the generator server) we might as well use it for

  • Converting Swagger 1.2 definitions into OpenAPI 2.0
  • Optionally use their validator for message compatibility

Problem with multipart-multifile post-body

After creating the code for nodejs I tried to start the project by npm start in the out-folder.

But I get an error message:

API Errors:

  #/paths/~1task~1/post/parameters/0: Not a valid parameter definition
    #/paths/~1task~1/post/parameters/0: Not a valid parameter definition
      #: Missing required property: schema
      #: Not a valid undefined definition
        #/type: No enum match for: object
        #/type: No enum match for: object
        #/type: No enum match for: object
        #/type: No enum match for: object
    #/paths/~1task~1/post/parameters/0: Missing required property: $ref

1 error and 0 warnings

The corresponding yaml-part:

  /task:
    post:
      tags:
        - app
      summary: create task
      operationId: createTask
      description: |
        todo
      responses:
        '200':
          description: OK
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                offerNumber: # metadata part
                  description: 'todo'
                  type: string
                trayImages: # image part
                  type: array
                  items:
                    type: string
                    format: base64
              required:
                - offerNumber
                - trayImages
            encoding:
              trayImages: 
                contentType: image/png, image/jpeg
        required: true

The idea behind this: The POST request must contain a kind of meta-data (the "offernumber"), and at least one image file. The number of images is not specified. It depends on how much the client wants to pass to the server.

See also: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#special-considerations-for-multipart-content

The API was designed with help of swaggerhub. And swagger-hub does not show me any error.

Can someone tell me what's wrong with my API?

Loading openapi-definition from Url is not possible

The description on npmjs.org says:

You can also load the OpenAPI definition from a URL.

But it does not work, as the config file path always gets resolved:
53. let configFile = path.resolve(configPath,configName)+'.json';

It would be nice, if definitions could be loaded by Url.

enumVars.name breaks python code

The code generation works fine, this package is really easy to use and to setup with custom configs or templates.

However I started using it to auto generate a client sdk for the App Center API from the App Center swagger.json.
When I tried running the sdk I solved the #23 changing the var name in python config from modelPackage to modelsPackage, but then another error came out from the enumVars that not manage well the name property:

let e = { name: v, value: '"'+v+'"' }; // insane, why aren't the quotes in the template?

It can be useful to change that to:

 let e = { name: Case.pascal(v), value: '"'+v+'"' };

or add another property to the dict, like it's done some lines below:

entry.nameInCamelCase = Case.pascal(entry.name); // for erlang-client

What's the suggested method? Eventually I can do a PR. ๐Ÿ‘

Throws on empty/falsy components.schemas

If a schema is provided w/ empty/falsy components.schemas, the following error is thrown:

YAMLException: unacceptable kind of an object to dump [object Undefined]

Different template engine

I got that the main goal of this project is to be able to use unmodified templates from OpenAPITools project. However the mustache templates do not allow to control whitespace. I got a partial almost a thousand characters in length. Which makes it almost impossible to maintain if template itself is not indented. The usual workaround people use is to indent template for maintainability and then use code reformatting tools to remove extra lines from generated code. Unfortunately I work with the language which doesn't have good code reformatting tools which can spit the code using the code style of my project.

It would be nice if we could replace mustache with something else (I totally understand if we cannot). One of the options I know off is https://handlebarsjs.com/

$ref not supported in api (path) params

When referencing a component via $ref as a param type, the resolved datatype on the parameter (accessed via allParams) is number and isEnum is false.
Now with this resulting model there's no possibility to correctly resolve the enum name.
Consider the following schema:

...
'/user/{type}':
    get:
      tags:
        - GetUsers
      summary: GetUsersByType
      operationId: GetUsersByType
      parameters:
        - name: type
          in: path
          required: true
          schema:
            $ref: '#/components/schemas/UserType'
      responses:
        '200':
          ...
components:
  schemas:
    UserType:
      enum:
        - 0
        - 1
        - 2
        - 3
        - 4
        - 5
      type: integer
      format: int32
      x-enum-varnames:
        - TypeA
        - TypeB
        - TypeC
        - TypeD
        - TypeE
        - TypeF

This is the result:

"allParams": [
                {
                  "isHeaderParam": false,
                  "isQueryParam": false,
                  "isPathParam": true,
                  "isBodyParam": false,
                  "isFormParam": false,
                  "paramName": "type",
                  "baseName": "type",
                  "required": true,
                  "optional": false,
                  "dataType": "number",
                  "%dataType%": "number",
                  "format": "int32",
                  "enum": [
                    0,
                    1,
                    2,
                    3,
                    4,
                    5
                  ],
                  "example": "0",
                  "isBoolean": false,
                  "isPrimitiveType": false,
                  "dataFormat": "int32",
                  "isDate": false,
                  "isDateTime": false,
                  "description": "",
                  "isFile": false,
                  "isEnum": false,
                  "vendorExtensions": {},
                  "-first": true,
                  "-last": false,
                  "hasMore": true
                }
]

Error: Cannot find module 'js-yaml'

I get the following error when running the example. Any help is much appreciated!

$ node cg --verbose nodejs defs/generator.yaml
module.js:529
    throw err;
    ^

Error: Cannot find module 'js-yaml'
    at Function.Module._resolveFilename (module.js:527:15)
    at Function.Module._load (module.js:476:23)
    at Module.require (module.js:568:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/asheqimran/Development/github.com/Mermade/openapi-codegen/cg.js:8:14)
    at Module._compile (module.js:624:30)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)

Maximum call stack size exceeded with gmail api from APIs-guru/openapi-directory

When running the generator against https://github.com/APIs-guru/openapi-directory/blob/master/APIs/googleapis.com/gmail/v1/swagger.yaml it crashes with the following error:

$ cg typescript-node ~/Downloads/swagger.yaml

{ level: 'Error',
  elementType: 'Context',
  elementId: '#/',
  message: 'Maximum call stack size exceeded' }
/Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:717
function traverse(schema, options, spec) {
                 ^

RangeError: Maximum call stack size exceeded
    at traverse (/Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:717:18)
    at /Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:582:43
    at Array.forEach (<anonymous>)
    at sampleObject (/Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:576:36)
    at traverse (/Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:782:17)
    at sampleArray (/Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:446:45)
    at traverse (/Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:782:17)
    at /Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:582:43
    at Array.forEach (<anonymous>)
    at sampleObject (/Users/fabian/.nvm/versions/node/v10.9.0/lib/node_modules/openapi-codegen/node_modules/openapi-sampler/dist/openapi-sampler.js:576:36)

$ node --version
v10.9.0
$ npm --version
6.2.0

Doesn't support specification in JSON?

OpenAPI specs can be either YAML or JSON. Loading JSON spec with openapi-codegen resulted in error:

hubiel@myhost ~/w/api-spec> node_modules/openapi-codegen/cg.js --verbose nodejs openapi.json 
Loaded config nodejs
Loaded definition openapi.json

/home/hubiel/work/api-spec/node_modules/js-yaml/lib/js-yaml/dumper.js:748
      throw new YAMLException('unacceptable kind of an object to dump ' + type);
      ^
YAMLException: unacceptable kind of an object to dump [object Undefined]
    at writeNode (/home/hubiel/work/api-spec/node_modules/js-yaml/lib/js-yaml/dumper.js:748:13)
    at writeBlockMapping (/home/hubiel/work/api-spec/node_modules/js-yaml/lib/js-yaml/dumper.js:627:10)
    at writeNode (/home/hubiel/work/api-spec/node_modules/js-yaml/lib/js-yaml/dumper.js:720:9)
    at dump (/home/hubiel/work/api-spec/node_modules/js-yaml/lib/js-yaml/dumper.js:809:7)
    at Object.safeDump (/home/hubiel/work/api-spec/node_modules/js-yaml/lib/js-yaml/dumper.js:815:10)
    at Object.transform (/home/hubiel/work/api-spec/node_modules/openapi-codegen/adaptor.js:683:32)
    at Object.main (/home/hubiel/work/api-spec/node_modules/openapi-codegen/index.js:30:13)
    at main (/home/hubiel/work/api-spec/node_modules/openapi-codegen/cg.js:155:19)
    at Object.<anonymous> (/home/hubiel/work/api-spec/node_modules/openapi-codegen/cg.js:197:4)
    at Module._compile (module.js:643:30)

The same definition was parsed without problems by swagger-node-codegen. It looks to me that openapi-codegen attempts to parse every input spec as YAML regardless of file extension or content.

Help Offer: Marshal Tests

Hi Team,

Excellent project, I love the approach with config files and templates, will really help to move away from the language specific java coding in the 'original'.

There are a couple of things I wanted to change to fix the go client generation, e.g. making the baseName parameter on a model ignore modelPropertyNaming, I believe this parameter is used to refer to the JSON or XML name in the produced API, so should be the original casing as defined in the swagger template. (e.g. in Go, it's the tag on the struct field, where name is the CamelCase exported name)

Making that change seems pretty high risk, so I was thinking: I could write a test which compares the cached version of the generated code off Petstore with what the project and templates currently generate. Any difference would be a fail, it would be expected that changes are manually reviewed then checked in. This would catch unexpected changes to languages, and it would make it obvious in a PR what changes are being made to the generated code. However it might also make changes slower, annoying things like white-space changes would count as test fails

Is this something which would benefit the project, or do you believe it would hinder? If it's useful and inline with where you are heading, I can write that over the next few days.

Migrating to TypeScript?

Great work!

Any interest in migrating to TypeScript? Pros and Cons?

I took a first step stab at it here. https://github.com/chauey/openapi-codegen

With Visual Studio Code, to run

  • ctrl ` (to open terminal)
  • npm install
  • ctrl-shift-b -> "tsc: build"
  • f5 (to debug with default params in .vscode/launch.json)

I wonder how best to keep things in sync if no migration to TypeScript but I want to continue to use TypeScript.

Next step I think would be to add interface for the models and remove any "any" types.

Thoughts?

`oneOf` support via Discriminated Unions

Many of the target languages support Union types.
e.g. for TypeScript, I think oneOf could be rendered as Discriminated Unions.

Does openapi-codegen support these at the moment? I see one mention of it in the templates, inside of the htmlDocs2 template. It looks like it is just introspecting the root object, though. It would be nice to see them treated as a 1st class template object similar to enums and "generics"

Example

components:
  schemas:
    ObjA:
      properties: ...
    ObjB:
      properties: ...
    ObjC:
      properties: ...
    Foo:
      oneOf:
        - $ref: "#/components/schemas/ObjA"
        - $ref: "#/components/schemas/ObjB"
        - $ref: "#/components/schemas/ObjC"

Should result in

export type Foo =  ObjA | ObjB | ObjC;

An in-range update of webpack is breaking the build ๐Ÿšจ

The devDependency webpack was updated from 4.32.2 to 4.33.0.

๐Ÿšจ View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

webpack is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • โŒ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v4.33.0

Features

  • add target: "electron-preload" for electron 5
    • renderer should use target: "web" in electron 5

Bugfixes

  • fix HMR rejection of removed and readded self-accepted modules
Commits

The new version differs by 21 commits.

  • d45bec3 4.33.0
  • 96869d9 Merge pull request #9191 from webpack/dependabot/npm_and_yarn/chrome-trace-event-1.0.2
  • e90cf7c Merge pull request #9190 from webpack/dependabot/npm_and_yarn/terser-webpack-plugin-1.3.0
  • 96b97b5 Downstream bug fixed and we can remove workaround
  • 31dae4d update snapshots
  • faba6e4 Merge pull request #9209 from webpack/dependabot/npm_and_yarn/@types/node-10.14.8
  • f571d78 Merge pull request #9205 from webpack/dependabot/npm_and_yarn/typescript-3.5.1
  • f59f31d chore(deps-dev): bump @types/node from 10.14.7 to 10.14.8
  • 289c520 chore(deps-dev): bump typescript from 3.4.5 to 3.5.1
  • c408ff5 Merge pull request #9202 from webpack/bugfix/9198
  • 46b428b fix rejection when removing and readding self-accepted module
  • 671cb18 Merge pull request #9188 from kwonoj/electron-preload-target
  • 4345fc5 chore(deps): bump chrome-trace-event from 1.0.0 to 1.0.2
  • 8712474 chore(deps): bump terser-webpack-plugin from 1.2.4 to 1.3.0
  • 2ec75c1 feat(target): support electron preload async chunk loading

There are 21 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those donโ€™t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot ๐ŸŒด

An in-range update of webpack is breaking the build ๐Ÿšจ

Version 4.17.3 of webpack was just published.

Branch Build failing ๐Ÿšจ
Dependency webpack
Current Version 4.17.2
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

webpack is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • โŒ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes v4.17.3

Bugfixes

  • Fix exit code when multiple CLIs are installed
  • No longer recommend installing webpack-command, but still support it when installed
Commits

The new version differs by 7 commits.

  • ee27d36 4.17.3
  • 4430524 Merge pull request #7966 from webpack/refactor-remove-webpack-command-from-clis
  • b717aad Show only webpack-cli in the list
  • c5eab67 Merge pull request #8001 from webpack/bugfix/exit-code
  • 943aa6b Fix exit code when multiple CLIs are installed
  • 691cc94 Spelling
  • 898462d refactor: remove webpack-command from CLIs

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those donโ€™t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot ๐ŸŒด

NPM publish latest package

Thanks for the great work! Is there any chance you can publish the latest version to NPM? In particular, I would like the fix that picks up the --templates CLI argument.

[Angular6] UnhandledPromiseRejectionWarning

FYI, got this deprecation warning after build.

(node:7948) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '...\TypeScriptAngular6Client\.ng_pkg_build\some-api\out\node_modules\rxjs\internal\Subject.d.ts'
(node:7948) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7948) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

An in-range update of yargs is breaking the build ๐Ÿšจ

The dependency yargs was updated from 13.2.2 to 13.2.4.

๐Ÿšจ View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

yargs is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • โŒ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 14 commits.

  • a6e67f1 chore(release): 13.2.4
  • fc13476 chore: update standard-verison dependency
  • bf46813 fix(i18n): rename unclear 'implication failed' to 'missing dependent arguments' (#1317)
  • a3a5d05 docs: fix a broken link to MS Terminology Search (#1341)
  • b4f8018 build: add .versionrc that hides test/build
  • 0c39183 chore(release): 13.2.3
  • 08e0746 chore: update deps (#1340)
  • 843e939 docs: make --no- boolean prefix easier to find in the docs (#1338)
  • 84cac07 docs: restore removed changelog of v13.2.0 (#1337)
  • b20db65 fix(deps): upgrade cliui for compatibility with latest chalk. (#1330)
  • c294d1b test: accept differently formatted output (#1327)
  • ac3f10c chore: move .hbs templates into .js to facilitate webpacking (#1320)
  • 0295132 fix: address issues with dutch translation (#1316)
  • 9f2468e doc: clarify parserConfiguration object structure (#1309)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those donโ€™t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot ๐ŸŒด

An in-range update of yaml is breaking the build ๐Ÿšจ

The dependency yaml was updated from 1.5.1 to 1.6.0.

๐Ÿšจ View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

yaml is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • โŒ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 7 commits.

  • f8d35f4 1.6.0
  • 4e31851 Update dependencies
  • cac058b Update docs
  • 0b1f8bc Add Document#directivesEndMarker
  • ebf59d9 cst: Add directives-end and document-end marker ranges to Document during parse
  • 2fa7f54 Allow same-column end for flow collections (Fixes #113, fixes #114, ref #108)
  • 2906c26 Drop custom source``, get it from common-tags instead

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those donโ€™t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot ๐ŸŒด

RequestBody types

What can we expect will be the plan for code generation, for the RequestBody for cases 1) and 2) below?

1) Multiple content-types with the same Schema

        "requestBody": {
          "description": "Pet object that needs to be added to the store",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            },
            "application/xml": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          },
          "required": false
        },

2) Multiple content-types with different Schemas

Schemas can vary by media type.

https://swagger.io/docs/specification/describing-request-body/

        "requestBody": {
          "description": "Pet object that needs to be added to the store",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Cat"
              }
            },
            "application/xml": {
              "schema": {
                "$ref": "#/components/schemas/Dog"
              }
            }
          },
          "required": false
        },

3) the AnyOf keyword

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! ๐ŸŽŠ

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If youโ€™re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didnโ€™t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didnโ€™t touch job or matrix configurations because these tend to be quite specific and complex, and itโ€™s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what youโ€™re doing it may require additional work or may not be applicable at all. Weโ€™re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, Iโ€™m a humble robot and wonโ€™t feel rejected ๐Ÿค–


FAQ and help

There is a collection of frequently asked questions. If those donโ€™t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot ๐ŸŒด

adaptor.js should support separate filename casing

I'm approaching this from the perspective of trying to create a python client config.
Python PascalCases it's class names and snake_cases it's file names.
Right now, the config allows for setting modelNaming and modelPropertyNaming. modelNaming sets the style for both the name, classname, and classFilename.
In order to produce output identical to swagger-codegen, openapi-codegen needs a modelFileNaming property, or something so that files can be named correctly.

An in-range update of webpack is breaking the build ๐Ÿšจ

The devDependency webpack was updated from 4.25.0 to 4.25.1.

๐Ÿšจ View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

webpack is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • โŒ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v4.25.1

Bugfixes

  • fix replacement of compile-time constant expression when expression is a wrapped expression (string prefix and/or suffix).
Commits

The new version differs by 6 commits.

  • 2361995 4.25.1
  • e2a2016 Merge pull request #8338 from webpack/bugfix/issue-8293
  • babe736 replace prefix/postfix even when equal for wrapped context
  • dcd0d59 test for #8293
  • af123a8 Merge pull request #8334 from webpack/bugfix/lint
  • 36eb0bb move azure specific commands to azure-pipelines.yml

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those donโ€™t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot ๐ŸŒด

YAMLException: unacceptable kind of an object to dump [object Undefined]

Hi everyone i have an issue which prevent me from generating NodeJS code.

Here is my result, i wonder if it's related to me adding the security schemes.

cg nodejs C:\Users\Nelson\StudioProjects\...\api\swagger\openapi.json -o C:\Users\Nelson\StudioP
rojects\000\api\swagger\api2 --verbose
Loaded config nodejs
Loaded definition C:\Users\Nelson\StudioProjects\000\api\swagger\openapi.json

C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:754
      throw new YAMLException('unacceptable kind of an object to dump ' + type);
      ^
YAMLException: unacceptable kind of an object to dump [object Undefined]
    at writeNode (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:754:13)
    at writeBlockMapping (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:633:10)
    at writeNode (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:726:9)
    at writeBlockMapping (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:633:10)
    at writeNode (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:726:9)
    at writeBlockMapping (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:633:10)
    at writeNode (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:726:9)
    at dump (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:815:7)
    at Object.safeDump (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\node_modules\js-yaml\lib\js-yaml\dumper.js:821:10)
    at Object.transform (C:\Users\Nelson\AppData\Roaming\npm\node_modules\openapi-codegen\adaptor.js:707:32)

Here is my JSON openapi 3 spec :

{
  "openapi" : "3.0.0",
  "servers" : [ {
    "description" : "SwaggerHub API Auto Mocking",
    "url" : "https://virtserver.swaggerhub.com/000/000/1.0.0"
  } ],
  "info" : {
    "description" : "This is a simple API",
    "version" : "1.0.0",
    "title" : "Invoicing API",
    "contact" : {
      "email" : "000"
    },
    "license" : {
      "name" : "Apache 2.0",
      "url" : "http://www.apache.org/licenses/LICENSE-2.0.html"
    }
  },
  "tags" : [ {
    "name" : "admins",
    "description" : "Secured Admin-only calls"
  }, {
    "name" : "developers",
    "description" : "Operations available to regular developers"
  } ],
  "paths" : {
    "/invoices" : {
      "get" : {
        "tags" : [ "developers" ],
        "summary" : "list all invoices.",
        "security" : [ {
          "oAuth2Scheme" : [ "requester", "approver", "auditer" ]
        } ],
        "operationId" : "listInvoices",
        "description" : "Retrieves list of invoices\n",
        "parameters" : [ {
          "in" : "query",
          "name" : "searchString",
          "description" : "pass an optional search string for looking up inventory.",
          "required" : false,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "search results matching criteria",
            "content" : {
              "application/json" : {
                "schema" : {
                  "type" : "array",
                  "items" : {
                    "oneOf" : [ {
                      "$ref" : "#/components/schemas/InvoiceItem"
                    }, {
                      "$ref" : "#/components/schemas/SalariesInvoiceItem"
                    }, {
                      "$ref" : "#/components/schemas/DoubleRechargingInvoiceItem"
                    } ]
                  }
                }
              }
            }
          },
          "400" : {
            "description" : "bad input parameter"
          }
        }
      },
      "post" : {
        "tags" : [ "developers" ],
        "summary" : "adds an invoice item",
        "security" : [ {
          "oAuth2Scheme" : [ "requester" ]
        } ],
        "operationId" : "addinvoice",
        "responses" : {
          "201" : {
            "description" : "invoice item created"
          },
          "400" : {
            "description" : "invalid input, object invalid"
          },
          "409" : {
            "description" : "an existing item already exists"
          }
        },
        "requestBody" : {
          "content" : {
            "multipart/form-data" : {
              "schema" : {
                "type" : "object",
                "properties" : {
                  "filename" : {
                    "type" : "array",
                    "items" : {
                      "type" : "string",
                      "format" : "binary"
                    }
                  },
                  "invoiceItem" : {
                    "oneOf" : [ {
                      "$ref" : "#/components/schemas/InvoiceItem"
                    }, {
                      "$ref" : "#/components/schemas/SalariesInvoiceItem"
                    }, {
                      "$ref" : "#/components/schemas/DoubleRechargingInvoiceItem"
                    } ]
                  }
                }
              }
            }
          },
          "description" : "Invoice item to add"
        }
      }
    },
    "/invoices/{id}" : {
      "summary" : "Represents an invoice",
      "description" : "This resource represents an individual invoice in the system. Each invoice is identified by a numeric `id`.\n",
      "parameters" : [ {
        "in" : "path",
        "name" : "id",
        "schema" : {
          "type" : "integer"
        },
        "required" : true,
        "description" : "Invoice ID."
      } ],
      "put" : {
        "tags" : [ "developers" ],
        "summary" : "Update an invoice item",
        "security" : [ {
          "oAuth2Scheme" : [ "requester" ]
        } ],
        "operationId" : "updinvoice",
        "responses" : {
          "200" : {
            "description" : "Invoice item updated."
          },
          "204" : {
            "description" : "No content"
          },
          "404" : {
            "description" : "ID not found."
          }
        },
        "requestBody" : {
          "content" : {
            "application/json" : {
              "schema" : {
                "$ref" : "#/components/schemas/InvoiceItem"
              }
            }
          },
          "description" : "Invoice item to add"
        }
      },
      "patch" : {
        "tags" : [ "developers" ],
        "summary" : "Change an invoice\\'s state",
        "security" : [ {
          "oAuth2Scheme" : [ "approver", "requester" ]
        } ],
        "operationId" : "patchinvoice",
        "description" : "Update an invoice to the system.",
        "responses" : {
          "204" : {
            "description" : "invoice item updated"
          },
          "404" : {
            "description" : "Resource not found."
          },
          "409" : {
            "description" : "Conflicting States."
          }
        },
        "requestBody" : {
          "content" : {
            "application/json" : {
              "schema" : {
                "type" : "object",
                "properties" : {
                  "oldState" : {
                    "type" : "string"
                  },
                  "newState" : {
                    "type" : "string"
                  },
                  "newOwner" : {
                    "type" : "string"
                  }
                }
              }
            }
          },
          "description" : "Invoice item to add"
        }
      }
    }
  },
  "components" : {
    "securitySchemes" : {
      "oAuth2Scheme" : {
        "type" : "oauth2",
        "description" : "This API uses OAuth 2 with the implicit grant flow. [More info](https://api.example.com/docs/auth)",
        "flows" : {
          "password" : {
            "tokenUrl" : "/oauth2/token",
            "scopes" : {
              "requester" : "Requester role",
              "approver" : "Approver role",
              "auditer" : "Audit role"
            }
          }
        }
      }
    },
    "schemas" : {
      "InvoiceItem" : {
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer",
            "readOnly" : true
          },
          "originalInvoiceReferenceNumber" : {
            "type" : "integer",
            "example" : "001"
          },
          "invoiceFromDetails" : {
            "$ref" : "#/components/schemas/InvoiceFromDetails"
          },
          "doubleReinvoicing" : {
            "type" : "boolean"
          },
          "entityToBeReinvoiced" : {
            "$ref" : "#/components/schemas/EntityToBeReinvoiced"
          },
          "reinvoicingDescription" : {
            "$ref" : "#/components/schemas/RechargingInvoiceDescription"
          },
          "rechargingInvoiceAmount" : {
            "$ref" : "#/components/schemas/RechargingInvoiceAmount"
          },
          "note" : {
            "type" : "string"
          }
        },
        "required" : [ "id", "originalInvoiceReferenceNumber", "invoiceFromDetails", "doubleReinvoicing", "reinvoicingDescription", "rechargingInvoiceAmount" ]
      },
      "SalariesInvoiceItem" : {
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer",
            "readOnly" : true
          },
          "originalInvoiceReferenceNumber" : {
            "type" : "integer",
            "example" : "001"
          },
          "invoiceFromDetails" : {
            "$ref" : "#/components/schemas/InvoiceFromDetails"
          },
          "doubleReinvoicing" : {
            "type" : "boolean"
          },
          "entityToBeReinvoiced" : {
            "$ref" : "#/components/schemas/EntityToBeReinvoiced"
          },
          "reinvoicingDescription" : {
            "$ref" : "#/components/schemas/RechargingInvoiceDescription"
          },
          "salariesDetails" : {
            "$ref" : "#/components/schemas/SalariesDetails"
          },
          "note" : {
            "type" : "string"
          }
        },
        "required" : [ "id", "originalInvoiceReferenceNumber", "invoiceFromDetails", "reinvoicingDescription", "doubleReinvoicing", "entityToBeReinvoiced", "salariesDetails", "note" ]
      },
      "DoubleRechargingInvoiceItem" : {
        "type" : "object",
        "properties" : {
          "id" : {
            "type" : "integer",
            "readOnly" : true
          },
          "originalInvoiceReferenceNumber" : {
            "type" : "integer",
            "example" : "001"
          },
          "invoiceFromDetails" : {
            "$ref" : "#/components/schemas/InvoiceFromDetails"
          },
          "doubleReinvoicing" : {
            "type" : "boolean"
          },
          "intermediaryEntity" : {
            "$ref" : "#/components/schemas/IntermediaryEntity"
          },
          "entityToBeReinvoiced" : {
            "$ref" : "#/components/schemas/EntityToBeReinvoiced"
          },
          "reinvoicingDescription" : {
            "$ref" : "#/components/schemas/RechargingInvoiceDescription"
          },
          "rechargingInvoiceAmount" : {
            "$ref" : "#/components/schemas/RechargingInvoiceAmount"
          },
          "salariesDetails" : {
            "$ref" : "#/components/schemas/SalariesDetails"
          },
          "note" : {
            "type" : "string"
          }
        },
        "required" : [ "id", "originalInvoiceReferenceNumber", "invoiceFromDetails", "doubleReinvoicing", "intermediaryEntity", "entityToBeReinvoiced", "reinvoicingDescription", "rechargingInvoiceAmount", "salariesDetails", "note" ]
      },
      "InvoiceFromDetails" : {
        "type" : "object",
        "properties" : {
          "entityDescription" : {
            "type" : "string",
            "example" : "Coordination France - 0034"
          },
          "hfmEntityCode" : {
            "type" : "string",
            "example" : "0034"
          },
          "accountingContact" : {
            "type" : "string",
            "example" : "Accountant #42"
          },
          "requester" : {
            "type" : "string",
            "example" : "Lee-Anne"
          },
          "department" : {
            "type" : "string",
            "example" : "Name Of Department"
          },
          "departmentManager" : {
            "type" : "string",
            "example" : "N+1"
          },
          "costCenter" : {
            "type" : "string"
          }
        },
        "required" : [ "entityDescription", "hfmEntityCode", "accountingContact", "requester", "department", "departmentManager", "costCenter" ]
      },
      "IntermediaryEntity" : {
        "type" : "object",
        "properties" : {
          "entityDescription" : {
            "type" : "string",
            "example" : "Description of the Entity"
          },
          "hfmEntityCode" : {
            "type" : "string",
            "example" : "0141"
          },
          "contactName" : {
            "type" : "string",
            "example" : "Contact's name"
          }
        },
        "required" : [ "entityDescription", "hfmEntityCode", "contactName" ]
      },
      "EntityToBeReinvoiced" : {
        "type" : "object",
        "properties" : {
          "entityDescription" : {
            "type" : "string",
            "example" : "Description of the Entity"
          },
          "hemEntityCode" : {
            "type" : "string",
            "example" : "0141"
          },
          "costCenter" : {
            "type" : "string",
            "example" : "Cost Center Name"
          },
          "commercialDepartment" : {
            "type" : "string",
            "example" : "Type Department"
          },
          "commercialDepartmentManager" : {
            "type" : "string",
            "example" : "Manager's name"
          },
          "contactName" : {
            "type" : "string",
            "example" : "Contact's name"
          }
        },
        "required" : [ "entityDescription", "hemEntityCode", "costCenter", "commercialDepartment", "commercialDepartmentManager", "contactName" ]
      },
      "RechargingInvoiceDescription" : {
        "type" : "object",
        "properties" : {
          "projectName" : {
            "type" : "string",
            "example" : "Project Name"
          },
          "reinvoiceDescription" : {
            "type" : "string",
            "example" : "Description"
          },
          "invoiceType" : {
            "type" : "string",
            "example" : "Type O Negative"
          },
          "transferPricingCategory" : {
            "type" : "string",
            "example" : "Cat 42"
          },
          "recurring" : {
            "type" : "boolean"
          },
          "expenseBasedOn" : {
            "type" : "string",
            "example" : "Something"
          },
          "amountIs" : {
            "type" : "string",
            "example" : "Something"
          },
          "relatedToHeadcountStaffCosts" : {
            "type" : "boolean"
          }
        },
        "required" : [ "projectName", "reinvoiceDescription", "invoiceType", "transferPricingCategory", "recurring", "expenseBasedOn", "amountIs", "relatedToHeadcountStaffCosts" ]
      },
      "RechargingInvoiceAmount" : {
        "type" : "object",
        "properties" : {
          "currency" : {
            "type" : "string",
            "example" : "USD"
          },
          "amountLines" : {
            "type" : "array",
            "items" : {
              "$ref" : "#/components/schemas/AmountLine"
            }
          },
          "markUp" : {
            "type" : "number",
            "format" : "float"
          },
          "totalWithoutVAT" : {
            "type" : "number",
            "format" : "float"
          },
          "vat" : {
            "type" : "number",
            "format" : "float"
          },
          "totalWithVAT" : {
            "type" : "number",
            "format" : "float"
          }
        },
        "required" : [ "currency" ]
      },
      "AmountLine" : {
        "type" : "object",
        "properties" : {
          "itemCode" : {
            "type" : "string",
            "example" : "Code 007"
          },
          "itemDescription" : {
            "type" : "string",
            "example" : "Description"
          },
          "quantity" : {
            "type" : "integer"
          },
          "pricePerUnit" : {
            "type" : "number",
            "format" : "float"
          },
          "globalSCOA" : {
            "type" : "string",
            "example" : "GlobalSCOA"
          },
          "localAccount" : {
            "type" : "string",
            "example" : "Receiving Entity"
          },
          "itemTotal" : {
            "type" : "number",
            "format" : "float"
          }
        },
        "required" : [ "itemCode", "itemDescription", "quantity", "pricePerUnit", "globalSCOA", "localAccount", "itemTotal" ]
      },
      "SalariesDetails" : {
        "type" : "object",
        "properties" : {
          "department" : {
            "type" : "string",
            "example" : "R&D"
          },
          "employeesName" : {
            "type" : "string",
            "example" : "Bob Burnquist, Alain Dupont"
          },
          "currency" : {
            "type" : "string",
            "example" : "GBP"
          },
          "headcount" : {
            "type" : "integer"
          },
          "salaries" : {
            "type" : "number",
            "format" : "float"
          },
          "pensionCosts" : {
            "type" : "number",
            "format" : "float"
          },
          "profitSharing" : {
            "type" : "number",
            "format" : "float"
          },
          "socialCharges" : {
            "type" : "number",
            "format" : "float"
          },
          "healthAndLifeInsurance" : {
            "type" : "number",
            "format" : "float"
          },
          "relocationAllowance" : {
            "type" : "number",
            "format" : "float"
          },
          "companyCar" : {
            "type" : "number",
            "format" : "float"
          },
          "clothingAllowance" : {
            "type" : "number",
            "format" : "float"
          },
          "travelAndEntertainment" : {
            "type" : "number",
            "format" : "float"
          },
          "consulting" : {
            "type" : "number",
            "format" : "float"
          },
          "other" : {
            "type" : "number",
            "format" : "float"
          },
          "markUp" : {
            "type" : "integer"
          },
          "total" : {
            "type" : "number",
            "format" : "float"
          }
        },
        "required" : [ "department", "employeesName", "currency", "headcount" ]
      }
    }
  }
}```

python: required AND nullable

I'm modeling an existing api in an OpenAPI 3.0 spec.
A key thing across most of this particular API (like it or not) is that all fields must be present (they are all required), but most of the time the fields are nullable. Some APIs include the fields and never use them (ie they are always set to null), but try to send a request without the field and it fails. (A replacement API is in the works, but until then, legacy prevails...)

So, I tried to model this by listing the requestBody parameters, and adding all of them to required. Then, I marked the fields that can be null as nullable: true.

However, in the python model template, required results in:

{{#required}}
if {{name}} is None:
raise ValueError("Invalid value for `{{name}}`, must not be `None`") # noqa: E501
{{/required}}

Could this be updated to support nullable? So that if required and not nullable it raises the ValueError?

Exception on `cg --list`

Besides installation, is there something else that I need to do to list templates?

kitty@catbox:~$ cg --list og
internal/modules/cjs/loader.js:583
    throw err;
    ^

Error: Cannot find module '/home/kitty/configs/nodejs.json'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/usr/lib/node_modules/openapi-codegen/cg.js:71:48)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

Unable to use config file from in current working directory or with explicit extension using CLI

This is a very cool tool; thanks for your work on it! I've been playing around with it for a few minutes, and I ran into the following issue.

overview

I would like to use a custom config file with the CLI to generate my client, as none of the existing configs match my needs. The first named parameter of the CLI allows me to pass in a path to a config file, but it seems to arbitrarily prevent me from using any file in the current working directory.

expected behavior

Based on the README.md + CLI usage instructions, I would expect the following to work:

# specify a file in the cwd
cg ./custom-config ./openapi.json

# specify an absolute path to a file with its extension
cg /Users/user/project/custom-config.json ./openapi.json

actual behavior

# cg --verbose ./custom-config openapi.json
Error: ENOENT: no such file or directory, open '/Users/user/project/node_modules/openapi-codegen/configs/custom-config.json'

# cg --verbose /Users/user/project/custom-config.json openapi.json
Error: ENOENT: no such file or directory, open '/Users/user/project/custom-config.json.json'

notes + proposal

The code that reads the config file from the argument makes two errors, as I can see it:

openapi-codegen/cg.js

Lines 65 to 71 in 2cfc04c

let configStr = argv._[0] || 'nodejs';
let configName = path.basename(configStr);
let remoteConfig = configName.indexOf(':')>-1;
let configPath = path.dirname(configStr);
if (!configPath || (configPath === '.')) configPath = path.resolve(__dirname,'configs');
let configFile = path.join(configPath,configName)+'.json';
let config = remoteConfig ? { defaults: {} } : yaml.parse(fs.readFileSync(configFile,'utf8'), {prettyErrors: true});

  1. If the result of path.dirname on the config file arg is '.', assume the user was trying to load something from the project's configs folder
    • This behavior was introduced in 2ee8394, and I can't see anything from that commit to explain why that logic was introduced
  2. .json is always appended to the path string

proposal

I'm happy to open a PR to fix these issues! I think the following would be the appropriate changes:

  • Remove (configPath === '.') check
    • If path.dirname returns a directory, the CLI should assume the user has provided a file path relative to the cwd
  • Only add .json if path.extname on the basename returns an empty string
    • From reading the code, this may have the happy accident of allowing the user to specify a custom config as a .yml file

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.