fmvilas / swagger-node-codegen

An OpenAPI 3.x/Swagger 2 code generator for Node.js
Apache License 2.0
200 stars 55 forks source link

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

Closed tswaters closed 5 years ago

tswaters commented 5 years ago

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

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

Here's what is generated by the current template:

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

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

I've got a fix for this -- it's not ideal but should work for simple cases:

diff --git a/templates/express-server/src/api/routes/___.js b/templates/express-server/src/api/routes/___.js
index ca65fd4..5bd1fd5 100644
--- a/templates/express-server/src/api/routes/___.js
+++ b/templates/express-server/src/api/routes/___.js
@@ -13,6 +13,9 @@ const router = new express.Router();
  */
 router.{{@key}}('{{../../subresource}}', async (req, res, next) => {
   const options = {
+    {{#if ../requestBody}}
+    body: req.body{{#compare (lookup ../parameters 'length') 0 operator = '>' }},{{/compare}}
+    {{/if}}
     {{#each ../parameters}}
       {{#equal this.in "query"}}
     {{../name}}: req.query.{{../name}}{{#unless @last}},{{/unless}}

My handlebars-foo is insufficient for full parsing here. Instead of passing the whole body along it should be possible to pick out individual properties... also, one could include multipart/form-data which isn't supported here at all -- would need a special body parser to pull out the data properly.

This sort of thing might be good candidate for a special helper or maybe mutating/constructing the data before it even hits handlebars. Here's an example of what another codegen library does with parameters/requestBody -- https://github.com/Mermade/openapi-codegen/blob/master/adaptor.js#L189

i.e., it does a lot of construction ahead of time so the template can be written a bit easier.

--

Anyway, I can send a PR to at least get this tweak in, so at least it's not totally missing the requestbody in the service.