OpenAPITools / openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
https://openapi-generator.tech
Apache License 2.0
21.81k stars 6.58k forks source link

[BUG] Default nodejs-express-server generation not runnable in default express: error: undefined {"service":"user-service"} #5190

Open d3vopz-net opened 4 years ago

d3vopz-net commented 4 years ago

Bug Report Checklist

Description

cannot run the default stub of nodejs-express-server. it creates a logger.js with winston and a user-service, which is not handled in the stub. the output of npm is

 error: undefined {"service":"user-service"}
 error: undefined {"service":"user-service"}

caused by created logger.js

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'user-service' },
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' }),
  ],
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({ format: winston.format.simple() }));
}

module.exports = logger;
openapi-generator version

openapitools/openapi-generator-cli:v4.2.3

OpenAPI declaration file content or url
openapi: '3.0.2'
info:
  title: Tree
  description: "d3vopz open api spec for tree operations"
  termsOfService: /terms-of-use
  version: '0.0.0'
  contact:
    name: "Tree API"
    url: "https://d3vopz.net/api"
    email: "d3vopz.net@gmail.com"
  license:
    name: "Don't use ;)"
    url: "https://d3vopz.net/license"
externalDocs: # Relative URL to external documentation
  url: /docs
  description: Find more info here
servers:
#  - url: '{protocol}://{environment}.{host}/v{versionId}{versionStage}{versionStageId}'
  - url: '{protocol}://{environment}.{host}/v{versionId}{versionStage}{versionStageId}'
    variables:
      protocol:
        enum:
          - http
          - https
        default: https
      environment:
        default: api    # Production server
        enum:
          - api         # Production server
          - api.dev     # Development server
          - api.staging # Staging server
      host:
        default: localhost # local server
#      versionId:
#        default: "1"   # 1st
#      versionStage:
#        default: ""    # stable
#        enum:
#          - ""         # stable stage
#          - "alpha"    # alpha stage
#          - "beta"     # beta stage
#      versionStageId:
#        default: ""    # stable (empty)
paths:
  /tree:
    get:
      tags:
      - Current tree data
      summary: "Call current node data."
      description: "Cet current node data."
      operationId: CurrentNodeData
      parameters:
      - name: idx
        in: query
        description: "nodes idx"
        schema:
          type: integer
          format: int64
      responses:
        200:
          description: Successful response
          content:
            application/json:
              schema:
                title: Sample
                type: object
                properties:
                  placeholder:
                    type: string
                    description: Placeholder description
        404:
          description: Not found response
          content:
            text/plain:
              schema:
                title: Node not found
                type: string
                example: Not found
Command line used for generation

create the stub with: openapitools/openapi-generator-cli:v4.2.3 generate -i /local/openapi.yml -g nodejs-express-server -o /local/out/nodejs-express-server

running the stub in npm --prefix /data start where /data contains the stub

Steps to reproduce

see command line

Related issues/PRs

Did not find a similiar issue

Suggest a fix

providing an example how to get it simple running with winston or disable complex winston log as default? idk

auto-labeler[bot] commented 4 years ago

πŸ‘ Thanks for opening this issue! 🏷 I have applied any labels matching special text in your issue.

The team will review the labels and make any necessary changes.

Nik-Novak commented 4 years ago

This is also happening to me with the v3 petstore.yaml definition

nuno-silva commented 4 years ago

Does anyone know of any workaround for this? I should add that I'm fairly new to Node.js.

wing328 commented 4 years ago

cc @YishTish

OnkelTem commented 4 years ago

Same here.

Now both swagger-codegen is glitchy and cannot be overridden and this doesn't work either... So basically we are deprived of any legal way to run a trivial mock server. Great.

OnkelTem commented 4 years ago

Hi @d3vopz-net. Have you managed to resolve it or found a workaround?

OnkelTem commented 4 years ago

After some debugging I reached a spot in

express-openapi-validator/
  dist/
    middlewares/
      openapi.request.validator.js

where the error is triggered, startin from line 72:

        if (this._apiDocs.components.requestBodies) {
            Object.entries(this._apiDocs.components.requestBodies).forEach(([id, schema]) => {
                // TODO add support for content all content types
                ajv.addSchema(schema.content[TYPE_JSON].schema, `#/components/requestBodies/${id}`);
            });
        }

Specifically, this one triggers the error:

ajv.addSchema(schema.content[TYPE_JSON].schema, `#/components/requestBodies/${id}`);

allegedly because schema.content may not have 'application/json' key and in my case has multipart/form-data instead.

UPDATE. After more testing I found the block raising the problem:

  /system/upgrade:
    post:
      summary: Upgrade device
      operationId: upgradeDevice
      security:
        - bearerAuth: []
      tags:
        - system
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                # 'file' will be the field name in this multipart request
                file:
                  type: string
                  format: binary
      responses:
        200:
          description: Successful operation
        401:
          $ref: "#/components/responses/Unauthorized"
        default:
          $ref: "#/components/responses/Error"

As you can see, content contains multipart/form-data key.

YishTish commented 4 years ago

I have pushed today a significant change to the module - took care of form-data as well. It's still processing the pull request. I will update you as soon as you can download an update

On Sun, 22 Mar 2020, 18:16 Artiom Neganov, notifications@github.com wrote:

After some debugging I reached a spot in express-openapi-validator/dist/middlewares/openapi.request.validator.js where the error is triggered, startin from line 72:

    if (this._apiDocs.components.requestBodies) {
        Object.entries(this._apiDocs.components.requestBodies).forEach(([id, schema]) => {
            // TODO add support for content all content types
            ajv.addSchema(schema.content[TYPE_JSON].schema, `#/components/requestBodies/${id}`);
        });
    }

Specifically, this one triggers the error:

ajv.addSchema(schema.content[TYPE_JSON].schema, #/components/requestBodies/${id});

allegedly because schema.content may not have 'application/json' key and in my case has multipart/form-data instead.

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/OpenAPITools/openapi-generator/issues/5190#issuecomment-602233517, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAGOOLIT6E2HSWBLP2WEXUTRIY2W3ANCNFSM4KO2HLVA .

YishTish commented 4 years ago

Artium - can you please check now? There's been a major change in the code

On Sun, Mar 22, 2020 at 10:36 PM Yishai Landau yishail@gmail.com wrote:

I have pushed today a significant change to the module - took care of form-data as well. It's still processing the pull request. I will update you as soon as you can download an update

On Sun, 22 Mar 2020, 18:16 Artiom Neganov, notifications@github.com wrote:

After some debugging I reached a spot in express-openapi-validator/dist/middlewares/openapi.request.validator.js where the error is triggered, startin from line 72:

    if (this._apiDocs.components.requestBodies) {
        Object.entries(this._apiDocs.components.requestBodies).forEach(([id, schema]) => {
            // TODO add support for content all content types
            ajv.addSchema(schema.content[TYPE_JSON].schema, `#/components/requestBodies/${id}`);
        });
    }

Specifically, this one triggers the error:

ajv.addSchema(schema.content[TYPE_JSON].schema, #/components/requestBodies/${id});

allegedly because schema.content may not have 'application/json' key and in my case has multipart/form-data instead.

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/OpenAPITools/openapi-generator/issues/5190#issuecomment-602233517, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAGOOLIT6E2HSWBLP2WEXUTRIY2W3ANCNFSM4KO2HLVA .

--

Yishai Landau

C: 972-54-979-2080 T: 972-8-6333-960 E: yishail@gmail.com

OnkelTem commented 4 years ago

@YishTish sorry for the delay. I'm gonna check this out tomorrow and write back!

OnkelTem commented 4 years ago

@YishTish Hi! I've been playing with API for several days and it seems to work well.

Unfortunately another critical thing doesn't seem to work: none of the examples provided in the API definition file get used. And it wouldn't be a problem if I could edit templates to add those example, but no: when I add {{examples}} then instead of my data, it substitutes totally random reply.

And this is how I try to use it in service.mustache:

const {{{operationId}}} = ({{#allParams}}{{#-first}}{ {{/-first}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{#-last}} }{{/-last}}{{/allParams}}) => new Promise(
  async (resolve, reject) => {
    try {
      const examples = {};
      {{#examples}}
        examples['{{contentType}}'] = {{{example}}};
      {{/examples}}

I tried two spots for adding my example data. First - operation response level:

paths:
  /inputs:
    get:
      summary: All inputs data
      description: >-
        Returns a list of currently configured inputs
      operationId: showInputs
      tags:
        - inputs
      responses:
        200:
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Inputs"
              example: # This is IGNORED
                - asd: 1
                - asd: 2

Second - the schema level:

components:
  schemas:
    Inputs:
      type: array
      items:
        $ref: "#/components/schemas/Input"
      example: # This is IGNORED as well
        - a: 1
        - b: 2

Do you have any idea why it doesn't work? I guessed this is a part of the spec https://swagger.io/docs/specification/adding-examples/

YishTish commented 4 years ago

Hey,

Thanks very much for trying out the module, and for the feedback.

I'm not sure I understand where the problem is - I just ran the generator on the classic petstore openapi document, and got examples when I loaded localhost:3000/api-doc

Please, can you explain further what it is you're trying to do?

Thanks,

Yishai

On Fri, Apr 3, 2020 at 12:27 PM Artiom Neganov notifications@github.com wrote:

@YishTish https://github.com/YishTish Hi! I've been playing with API for several days and it seems to work well.

Unfortunately another critical thing doesn't seem to work: none of the examples provided in the API definition file get used. And it wouldn't be a problem if I could edit templates to add those example, but no: when I add {{examples}} then instead of my data, it substitutes totally random reply.

And this is how I try to use it in service.mustache:

const {{{operationId}}} = ({{#allParams}}{{#-first}}{ {{/-first}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{#-last}} }{{/-last}}{{/allParams}}) => new Promise( async (resolve, reject) => { try { const examples = {}; {{#examples}} examples['{{contentType}}'] = {{{example}}}; {{/examples}}

I tried two spots for adding my example data. First - operation response level:

paths: /inputs: get: summary: All inputs data description: >- Returns a list of currently configured inputs operationId: showInputs tags:

  • inputs responses: 200: description: Successful operation content: application/json: schema: $ref: "#/components/schemas/Inputs" example: # This is IGNORED
    • asd: 1
    • asd: 2

Second - the schema level:

components: schemas: Inputs: type: array items: $ref: "#/components/schemas/Input" example: # This is IGNORED as well

  • a: 1
  • b: 2

Do you have any idea why it doesn't work? I guessed this is a part of the spec https://swagger.io/docs/specification/adding-examples/

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/OpenAPITools/openapi-generator/issues/5190#issuecomment-608332727, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAGOOLPKQEH6X7SYJG2QGODRKWTXFANCNFSM4KO2HLVA .

--

Yishai Landau

C: 972-54-979-2080 T: 972-8-6333-960 E: yishail@gmail.com

frank-yoon commented 4 years ago

Hey, Thanks very much for trying out the module, and for the feedback. I'm not sure I understand where the problem is - I just ran the generator on the classic petstore openapi document, and got examples when I loaded localhost:3000/api-doc Please, can you explain further what it is you're trying to do? Thanks, Yishai …

Hi YishTish,

For me, the error: undefined {"service":"user-service"} is occurring when I generate a server stub from an OpenAPI 3.0.0 version of petstore.yaml. When I generate a server stub from the older Swagger 2.0 version of petstore.yaml, the server runs fine.

Thanks, Frank

wimjongman commented 3 years ago

Has this ever been resolved?

tastycrayon commented 3 years ago

Has this ever been resolved?

I could not find any ... in my express route I wrote throw new Error('could not get genre!!!') but I get this Screenshot 2021-03-30 at 12 34 34

I also tried logger.info(err); logger.log('info', err);

YishTish commented 3 years ago

Hey,

I tried running the generator on my end - pulled from master, ran generator, npm install, and node index.js - and it worked.

I ran it on a mac. Are both of you using Windows? Is there a step that I'm missing?

On Sun, Apr 4, 2021 at 12:30 AM Mosiur Rahman @.***> wrote:

Has this ever been resolved?

I could not find any ... in my express route I wrote throw new Error('could not get genre!!!') but I get this [image: Screenshot 2021-03-30 at 12 34 34] https://user-images.githubusercontent.com/37541747/113491913-044db800-94f6-11eb-8265-52392e94dc5d.png

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/OpenAPITools/openapi-generator/issues/5190#issuecomment-812928204, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAGOOLMG7GIJ6MINJWD6ESLTG6CHPANCNFSM4KO2HLVA .

--

Yishai Landau

C: 972-54-979-2080 T: 972-8-6333-960 E: @.***

Stokestack commented 2 years ago

I'm getting the same thing on Bullseye (Debian) Linux (on a Raspberry Pi), after generating code with 6.0.1.

This was after it had been running, but failing on every query because of the "request should have required property 'headers'" bug. I did an npm list and it claimed a bunch of dependencies were missing for express-openapi-validator (despite no errors being thrown on previous runs), so I did a manual npm install of express-openapi-validator alone. This had a bunch of deprecated or security-compromised modules, so I did a full update.

Now once again this entire server side is broken. Thanks to the OP's analysis of logger.js, I realize that this is just a generic uninformative error message that leaves us totally in the dark.