openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

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

Open d3vopz-net opened this issue 6 years ago • 17 comments

Bug Report Checklist

  • [x] Have you provided a full/minimal spec to reproduce the issue?
  • [x] Have you validated the input using an OpenAPI validator (example)?
  • [x] What's the version of OpenAPI Generator used?
  • [x] Have you search for related issues/PRs?
  • [x] What's the actual output vs expected output?
  • [ ] [Optional] Bounty to sponsor the fix (example)
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: "[email protected]"
  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

d3vopz-net avatar Feb 02 '20 15:02 d3vopz-net

👍 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.

auto-labeler avatar Feb 02 '20 15:02 auto-labeler

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

Nik-Novak avatar Feb 07 '20 04:02 Nik-Novak

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

nuno-silva avatar Mar 01 '20 19:03 nuno-silva

cc @YishTish

wing328 avatar Mar 02 '20 02:03 wing328

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 avatar Mar 22 '20 13:03 OnkelTem

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

OnkelTem avatar Mar 22 '20 13:03 OnkelTem

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.

OnkelTem avatar Mar 22 '20 16:03 OnkelTem

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, [email protected] 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 avatar Mar 22 '20 20:03 YishTish

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

  • a lot of work was done in the last couple of weeks...

On Sun, Mar 22, 2020 at 10:36 PM Yishai Landau [email protected] 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, [email protected] 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: [email protected]

YishTish avatar Mar 24 '20 16:03 YishTish

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

OnkelTem avatar Mar 29 '20 20:03 OnkelTem

@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/

OnkelTem avatar Apr 03 '20 09:04 OnkelTem

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 [email protected] 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: [email protected]

YishTish avatar Apr 04 '20 21:04 YishTish

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

frank-yoon avatar Apr 13 '20 02:04 frank-yoon

Has this ever been resolved?

wimjongman avatar Mar 18 '21 14:03 wimjongman

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);

tastycrayon avatar Apr 03 '21 21:04 tastycrayon

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: @.***

YishTish avatar Apr 06 '21 20:04 YishTish

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.

Stokestack avatar Jul 16 '22 00:07 Stokestack