Coder Social home page Coder Social logo

acr-lfr / generate-it Goto Github PK

View Code? Open in Web Editor NEW
7.0 7.0 4.0 3.24 MB

Generate-It from yml files

Home Page: https://acr-lfr.github.io/generate-it/

License: MIT License

JavaScript 1.93% Shell 0.35% TypeScript 89.24% Dockerfile 0.29% Nunjucks 8.19%
codegen nodejs openapi swagger template

generate-it's People

Contributors

acrontum-carmichael avatar acrontum-revah avatar acrontum-sanchez avatar acrontum-silva avatar celleb avatar dependabot[bot] avatar j-d-carmichael avatar jdcrecur avatar jonmanga avatar p-mcgowan avatar sergey-dudik avatar zewish avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

generate-it's Issues

[BUG] non-trivial top-level array types are not properly interfaced

Describe the bug
the test below, when added to /tests/generateTypeScriptInterfaceText.ts should not fail (it's a terrible test, but illustrates the problem.

  it('should convert crazy nested objects', async () => {
    const output = await generateTypeScriptInterfaceText('Crazy', `
      {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "categoryName": {
              "type": "string"
            },
            "settings": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "sid": {
                    "type": "string"
                  },
                  "enabled": {
                    "type": "boolean"
                  },
                  "translation": {
                    "type": "string"
                  },
                  "isChangeable": {
                    "type": "boolean"
                  },
                  "targetEnabled": {
                    "type": "string"
                  },
                  "descriptionShort": {
                    "type": "string"
                  },
                  "descriptionLong": {
                    "type": "string"
                  },
                  "descriptionDeaktivated": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
  `);

    process.stdout.write('\n\n' + `'${output.outputString}'` + '\n\n');
    expect(output.outputString).not.toBe(`
export interface Crazy {
    categoryName?: string;
    settings?:     Setting[];
}

export interface Setting {
    descriptionDeaktivated?: string;
    descriptionLong?:        string;
    descriptionShort?:       string;
    enabled?:                boolean;
    isChangeable?:           boolean;
    sid?:                    string;
    targetEnabled?:          string;
    translation?:            string;
}

`);
  });

To Reproduce
Steps to reproduce the behavior:

  1. ...

Expected behavior
A clear and concise description of what you expected to happen.
output should be something like

export type Crazy = CrazyObj[];
export interface CrazyOb {
    categoryName?: string;
    settings?:     Setting[];
}

export interface Setting {
    descriptionDeaktivated?: string;
    descriptionLong?:        string;
    descriptionShort?:       string;
    enabled?:                boolean;
    isChangeable?:           boolean;
    sid?:                    string;
    targetEnabled?:          string;
    translation?:            string;
}

or Array<{crazy}>
Node & NPM version

Operating system:

  • OS: [e.g. LinuxMint]
  • Version [e.g. 19.2]

Additional context
Add any other context about the problem here.

[BUG] git fetch fail with modified changes to the tpls

Describe the bug
The gitfetch fails when there have been local changes, but it doesn't bother trying again

To Reproduce
Steps to reproduce the behavior:

  1. change a file in the .openapi-nodegen folder and regen

Expected behavior
doesn't fail but git resets and tries again

Node & NPM version
14

Operating system:

  • OS: [e.g. LinuxMint]
  • Version 20

[BUG] default values on query param array not working

Example query parameter input:

in: query
name: getStage
required: false
type: array
items:
  type: string
  enum:
    - stageGet
    - stageGot
default:
  - stageGet
  - stageGot

The expected output would be that the Joi validator sets the default value to ['stageGet','stageGot']

The actual result is that no default option is produced

[CHORE] jest

This is currently running behind on jest 25 and still not on eslint (tslint).

Should be upgraded when someone is bored one day and finds a spare half hour.

[BUG]

Describe the bug
When the swagger file does not contain any definition, the node generation fails.

To Reproduce
Steps to reproduce the behavior:

  1. Create a swagger file without definitions
  2. Run the nodegen

Expected behavior
The node app generation should not fail

Node & NPM version
node v10.17

Operating system:

  • OS: Linux

Additional context

Date property not generated in the model

Date attributes are wrongly generated in the models.

Swagger object:

type: object properties: name: type: string model: type: string date: type: string format: date-time

Generated mock:

return mockItGenerator({ type: "object", properties: { name: { type: "string" }, model: { type: "string" }, date: { type: "string", format: "date-time" } } });

Expanded documentation

Currently the docs are a little sparse on the ground.

  • Example object the system builds and passes to the nunjucks tpl engine
  • Different nunjucks naming conventions
  • How the engine works
    • ___op|mock|interface|stub files
    • how the file cache and file diff system works to show the file diff between different files
    • The file diff system needs improving, currently it performs a file diff per path/method, instead it should build the entire cache file, and only then perform the cache file diff. This will result in more meaningful/easy to understand output

Array query params wrongly generated

When defining a query parameter like:

in: query name: products type: array required: true items: type: string

Then the generated interface looks like:

export default interface MarketToolProductsLanguageGetQuery { products: array; }

instead of:

export default interface MarketToolProductsLanguageGetQuery { products: Array<string> ; // or string[]; }

[BUG] Inline path params not working

Describe the bug
Inline path params not working.

To Reproduce
Steps to reproduce the behavior:

  1. Install and run Generate-it generate:nodegen script
  2. Run docker-compose up

Expected behavior
Server should run

Node & NPM version
Node: 16.13.1
NPM: 8.1.2

Operating system:

  • OS: Ubuntu
  • Version: 20.04.3 LTS

Additional context
Started a new Generate-it project using this swagger file: https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v2.0/yaml/petstore.yaml

For the swagger file mentioned above, the Api keeps returning the following:
src/http/nodegen/tests/PetsDomain.ts: undefined[id]

[BUG] output transformers strips out fields with anyOf schema

Describe the bug
Properties with anyOf schema are striped out from output transformers.

Given the following schemas:
user/model.yml

anyOf:
  - $ref: ./driver/model.yml
  - $ref: ./passenger/model.yml
discriminator:
  propertyName: type
type: object
properties:
  token:
    type: string
    readOnly: true
    example: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ5Y3BCVzRKSU0zYWVE...
  user:
    $ref: user/model.yml
required:
  - user
  - token

Produces

export default {
  // authorize
  authorize: {
    token: String
  }
}

To Reproduce
Steps to reproduce the behavior:

  1. Generate the backend from the swagger file
  2. Inspect the generated output transformer

Expected behavior
The transformer has the correct fields and types or at least allows any field to pass.

Node & NPM version
Node: 12.18.2
NPM: 6.14.8

Operating system:

  • OS: MacOS
  • Version: 11.2.2

Additional context
Using OAS3

[FEATURE] infer typings from parameters

Is your feature request related to a problem? Please describe.
When defining post body params, typings are any

for instance, the resulting yaml:

paths:
  /somethings:
    get:
      parameters:
        - $ref: '#/parameters/a'
        - $ref: '#/parameters/b'
        - $ref: '#/parameters/c'
      responses:
        '200':
          description: Ok
          schema:
            $ref: '#/definitions/SomethingModels'
        '404':
          description: Not found
    post:
      operationId: somethingPost
      parameters:
        - in: body
          name: something
          required: true
          schema:
            type: object
            required:
              - code
              - name
            properties:
              code:
                type: string
              name:
                type: string
              appId:
                type: number

the get route produces the correct typings, but the post route (since it has no definition models) is not inferred from the spec.
in this case, it seems like it should be able to produce the typings, possibly as follows:

export interface SomethingsPostBody {
  code: string;
  name: string;
  appId?: number;
}

Describe the solution you'd like
Depending on the extent of the solution, the ideal situation would be a path/method/paramtype named interface with the properties defined

Describe alternatives you've considered
The alternative is to make sure each body has a separate definition - this would be ok, but could require defining different types for post, patch, update. without template extension, this would likely mean much duplication, and maintenance.

[BUG] domain segment not producing proper routes

Describe the bug
The generator is not producing expected routes when used with segments.
The routes are camel-cased and the parameters are dropped.
Example of wrong routes:

export default function (app: express.Application, basePath = '') {
  
  app.use(basePath + '/auth', authRoutes())
    
  app.use(basePath + '/hr', hrRoutes())
    
  app.use(basePath + '/hrEmployees', hrEmployeesRoutes())
    
  app.use(basePath + '/hrRoles', hrRolesRoutes())
    
  app.use(basePath + '/hrUser-roles', hrUserRolesRoutes())
    
  app.use(basePath + '/hrUsers', hrUsersRoutes())
    
  app.use(basePath + '/permissions', permissionsRoutes())
 }

To Reproduce
Steps to reproduce the behavior:

  1. Use swagger definitions with nested routes
  2. set segmentFirstGrouping" 2 in .boatsrc
  3. Generate to the backend

Directory structure:
Screenshot 2020-09-02 at 09 41 27

Expected behavior
Something like this:

export default function (app: express.Application, basePath = '') {
  
  app.use(basePath + '/auth', authRoutes())
    
  app.use(basePath + '/hr', hrRoutes())
    
  app.use(basePath + '/hr/:id/employee', hrEmployeesRoutes())
    
  app.use(basePath + '/hr/:id/roles', hrRolesRoutes())
    
  app.use(basePath + '/hr/:id/user-roles', hrUserRolesRoutes())
    
  app.use(basePath + '/hr/:id/users', hrUsersRoutes())
    
  app.use(basePath + '/permissions', permissionsRoutes())
 }

Node & NPM version

Operating system:

  • OS: [e.g. LinuxMint]
  • Version [e.g. 19.2]

Additional context
Add any other context about the problem here.

[BUG] Unclear wording on package json diff

Describe the bug
ReGenerate an existing server after new changes to the package.json.njk in a remote tpl repo. The output diff doesn't clearly state what it means. It indicates the packages have actually been updated where as it should read the user should update them.

It should read:
"Some packages in the master template have been updated, please compare the table below and manually update your API"

MicrosoftTeams-image

[BUG] content negotiation should be case-insensitive

context:

2021-04-13T09:28:36.251Z error: Requested content-type "application/PDF" not supported  
2021-04-13T09:28:36.251Z error: HttpException: Not acceptable 
  at ServerResponse.res.inferResponseType (/code/build/src/http/nodegen/middleware/inferResponseType.js:28:23) 

client sends Accept: application/PDF, server produces application/pdf, explosions

spec is case insensitive

[ENH] Support all CLI options in .nodegenerc

What do you think?

instead of long lines and verbose package scripts, would be nice to just say generate:nodegen": "generate-it".

Then nodegen could just contain

{
  "nodegenDir": "src/http",
  "helpers": {
    "stub": {
      "requestType": "NodegenRequest"
    }
  },
  "confirm": true, // --yes
  "mocked": true,
  "templates": "github.com/p-mcgowan/burn-it-down",
  "inputSpec": "../swagger/build/api.yml"
}

[BUG] accessToken middleware not included in OA3 routes

Describe the bug
The accessToken middleware is not included OA3 routes

Current output:

  router.get(
    '/',
    celebrate(
      logsValidators.getLogs
    ) /* Validate the request data and return validation errors */,

    async (req: any, res: express.Response) => {
      return res
        .status(200)
        .json(
          objectReduceByMap(
            await LogsDomain.getLogs(req.jwtData, req.query),
            logsTransformOutputs.getLogs
          )
        );
    }
  );

To Reproduce
Define specifications with OA3 securitySchemes and routes that include security definitions.

Expected behavior
Routes include accessToken middleware.

  router.get(
    '/',
    accessTokenMiddleware([
      'Authorization',
    ]) /* Validate request security tokens */,

    celebrate(
      logsValidators.getLogs
    ) /* Validate the request data and return validation errors */,

    async (req: any, res: express.Response) => {
      return res
        .status(200)
        .json(
          objectReduceByMap(
            await LogsDomain.getLogs(req.jwtData, req.query),
            logsTransformOutputs.getLogs
          )
        );
    }
  );

Node & NPM version

Operating system:

  • OS: [e.g. LinuxMint]
  • Version [e.g. 19.2]

Additional context
Add any other context about the problem here.

[BUG] Joi validator body has duplicate field names when using OA3

Describe the bug
The generated joi validator body has duplicate field names, i.e,:

export default {
  registerUser: {
    body: {
      userName: Joi.string().required(),
      firstName: Joi.string().required(),
      lastName: Joi.string().required(),
      contactNumber: Joi.string().required(),
      emailAddress: Joi.string().required(),
      role: Joi.string().valid('Standard', 'Admin').required(),
      userName: Joi.string().required(),
      firstName: Joi.string().required(),
      lastName: Joi.string().required(),
      contactNumber: Joi.string().required(),
      emailAddress: Joi.string().required(),
      role: Joi.string().valid('Standard', 'Admin').required(),
    },
  },
}

To Reproduce
Steps to reproduce the behavior:

  1. Use Generated it with the following definitions
openapi: 3.0.0
info:
  version: 1.0.0
  title: The Best API
  description: Best API
  contact:
    name: Company
    email: [email protected]
    url: 'https://hello.me.com'
servers:
  - url: 'https://localhost:{port}/v1'
    variables:
      port:
        default: '8080'
paths:
  /users:
    get:
      tags:
        - users
      summary: Returns a collection of users
      operationId: getUsers
      parameters:
        - $ref: '#/components/parameters/QueryLimit'
        - $ref: '#/components/parameters/QuerySkip'
        - $ref: '#/components/parameters/QuerySort'
      responses:
        '200':
          description: Users successfully returned
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/UserResponse'
    post:
      tags:
        - users
      summary: Register a new user
      operationId: registerUser
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserPost'
      responses:
        '200':
          description: User successfully registered
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
   QueryLimit:
      name: limit
      in: query
      description: Limit the number of items return
      required: false
      schema:
        type: integer
      example: 10
    QuerySkip:
      name: skip
      in: query
      description: The number of items to skip
      required: false
      schema:
        type: integer
      example: 20
    QuerySort:
      name: sort
      in: query
      description: >-
        Sort the items on the specified field and order. i.e. name=1 to sort
        items in ascending order based on their name.
      required: false
      schema:
        type: string
  schemas:
    JwtAccess:
      allOf:
        - $ref: '#/components/schemas/UserPost'
    UserRole:
      type: string
      enum:
        - Standard
        - Admin
      example: Standard
    User:
      allOf:
        - $ref: '#/components/schemas/UserPost'
        - type: object
          properties:
            createdAt:
              type: string
            updateAt:
              type: string
    UserPost:
      type: object
      required:
        - userName
        - firstName
        - lastName
        - contactNumber
        - emailAddress
        - role
      properties:
        userName:
          type: string
        firstName:
          type: string
          example: Shikuvule
        lastName:
          type: string
          example: Tomanga
        contactNumber:
          type: string
          example: '+264813287027'
        emailAddress:
          type: string
          example: [email protected]
        role:
          $ref: '#/components/schemas/UserRole'
    UserResponse:
      type: object
      required:
        - data
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/User'

Expected behavior

There should be no duplicate field names

Node & NPM version
14

Operating system:

  • OS: [macOS Catalina]
  • Version [10.15.5]

Additional context
Add any other context about the problem here.

[BUG] OA3 path headers throw error

Describe the bug
A clear and concise description of what the bug is.

Nodegen version
5.0.1

To Reproduce
Steps to reproduce the behavior:

  1. use a header definition from the componentnts/parameters and generate in an OA3 file

Expected behavior
That it generates without error.

Node & NPM version
12 lts latests npm

Operating system:

  • OS: LinuxMint

[BUG] out of memory when diff'ing

Describe the bug

image

To Reproduce
Happens occasionally with npm run generate:nodegen

  "generate:nodegen": "generate-it ../user-management-swagger/build/api_1.0.0.yml -m -t https://github.com/acrontum/openapi-nodegen-typescript-server.git",

Expected behavior
Not out of memory

Node & NPM version
node: v13.13.0
npm: 6.14.5

Operating system:

  • OS: Ubuntu
  • Version 18.04.4 LTS

Additional context
Can't reproduce, running it again without making changes seems to work fine the second time

[FEATURE] Advance the template change log control

There is the changelog.generate-it.json option for templates now - this now can be extended to something far more sophisticated.

But for starters should clearly print the changes a dev needs to make to use the new template advancements..

You have to follow these steps to upgrade this server...

Create a defined list of change log [types] and react accordingly in the core.

[BUG] The request handler doesn't respect the type of the input as specified in the swagger.

Describe the bug
The request handler automatically converts a csv string to an array. It, therefore, breaks validation because the validator and the domain still expects a string. Conversely, when given a single value it assumes it's a string and doesn't convert it to a single value array. Therefore, also failing validation and Domain.

To Reproduce
Steps to reproduce the behavior:

  1. Define a path with a query parameter that takes a string.
  2. Generate the backend
  3. Send a request and set the query parameter to a csv i.e. url?select=name,surname

Steps to reproduce converse behavior:

  1. Define a path with a query parameter that takes a string array.
  2. Generate the backend
  3. Send a request and set the query parameter to a single string i.e. url?select=name

Expected behavior
The expected behaviour is that the request handler respects the type of the properties as specified in Swagger definitions.

Currently, in case one it will convert it to a string array and fails validation.
In case number two the input is left as is and fails validation because a string array was expected.

The workaround is to set csv to type string array and append a comma to the request query, but I'll have to filter out the null value in code.

Objects without properties are being ignored

Assuming I have the following definition:
Athlete.yml

type: object
  properties:
    firstName:
      type: string
    physicalDetails:
      type: object

The Interface generated by the Nodegen does not include the physicalDetails property, which is a generic object, looking like this:
Athlete.ts

export default interface Athlete {
  firstName?: string;
}

But when adding properties to the physicalDetails object, it does get generated.

Add models for transformers

Would be great to generate interfaces for the transformers.

I would like to use the following generated transformer as a type in other parts of the application.
`
export default {
// customerGet
customerGet: {
email: String,
firstName: String,
lastName: String
}
};

`
Would like to have something like this:

`
export interface CustomerGet {
email: String,
firstName: String,
lastName: String
}

export default {
// customerGet
customerGet: CustomerGet
};
`

[BUG]

Describe the bug
tsc complains about uuid/v4 types and implicit any's in process.ts

To Reproduce
Steps to reproduce the behavior:
npm i [email protected]
npm run generate:nodegen

Expected behavior
no compilation errors

Node & NPM version
node: v13.13.0
npm: 6.14.5

Operating system:

  • OS: ubuntu
  • Version 18.04.4

Additional context

src/http/nodegen/request-worker/process.ts(4,20): error TS7016: Could not find a declaration file for module 'uuid/v4'. '/home/patrickmcgowan/source/acrontum/bmw/dsd/user-management/user-management/node_modules/uuid/v4.js' implicitly has an 'any' type.
  Try `npm install @types/uuid` if it exists or add a new declaration (.d.ts) file containing `declare module 'uuid/v4';`
src/http/nodegen/request-worker/process.ts(40,32): error TS7031: Binding element 'callId' implicitly has an 'any' type.
src/http/nodegen/request-worker/process.ts(40,40): error TS7031: Binding element 'error' implicitly has an 'any' type.
src/http/nodegen/request-worker/process.ts(40,47): error TS7031: Binding element 'response' implicitly has an 'any' type.

temp fix:
npm i @types/uuid
replace

-      const handleMessage = ({ callId, error, response }) => {
+      const handleMessage = ({ callId, error, response }: any) => {

/src/http/nodegen/request-worker/process.ts

Inform of new package json updates

Currently when a new dependency is added or one removed or even updated.. this is not pushed to an already built ts or es server.

  1. A new release is published
  2. When updating an existing server, openapi-nodegen informs the user they should manually update their package json file.

[BUG] openapi-nodegen-api-file.yml parsing issues on MacOs

Describe the bug
There seems to be a parsing issue for the generated openapi-nodegen-api-file.yml file on MacOS.
It produces the following error when running the app:

Promise {
  <rejected> [ParseException [Error]: Unexpected characters (
      }
    },
    "servers": [
      {
        "url": "{protocol}://{host}:{port}",
        "variables": {
          "host": {
            "default": "localhost"
          },

The error is fixed by just resaving the file.

To Reproduce
Steps to reproduce the behavior:

  1. Generate the backend from a swagger file with generate-ti
  2. Start the application

Expected behavior
The application rune without issue.

Node & NPM version
Node: 12.18.2
NPM: 6.14.8

Operating system:

  • OS: MacOS
  • Version: 11.2.2

Additional context
The error is fixed by just resaving the file.

[FEATURE] accept helpers (files / folders)

Template renderer is already setup (simlarly to how boats works) to accept template helpers, but they are never actually passed in (see usages below). Would be cool to have a cli flag and nodegen option to pass in files and / or folders to be injected.

If we update the cli and nodegen options to accept something like -h file.js -h helpers/, this would allow us to keep template-specific logic out of the core. For instance, in ts-express we can just add in a helpers folder with all the ts-express -specific helper methods and not add to the ever-growing helpers folder(s) in here

template load is called from these 3 files, but the last 2 defaulted options are never used:
GenerateOperation
generateFile
GenerateInterfaceFiles

[BUG] Empty array inputs are not respected by the validator.

Describe the bug
Given an input definition that has an item of type array that's marked required, the validator fails the input when given an empty array. Even when the minItems is set to 0. Empty arrays should be valid inputs unless specified otherwise.

To Reproduce
Steps to reproduce the behavior:

  1. Define an input object with one more property as required arrays.
    For example
type: object
required:
- items
properties:
  items:
    type: array
    items:
      type: string

Expected behavior
An empty array should pass the validation
For example, given the following input:

{
    "items":[]
}

Should pass the validation.

[BUG] Generate-it fails to report missing package until there are more than 1

Describe the bug
A clear and concise description of what the bug is.
generate-it output does not contain quick fix section when building, required node_module never listed, tests fail

To Reproduce
use this package json - it's missing request-promise-router.
add some api file to ./api.yml (used oa3, don't think it matters)
npm i
npm run gen

notice no message about missing packages
removing another node module from the deps list causes both to show up (sometimes?). It's actually pretty inconsistent

{
  "name": "my-sweet-project",
  "description": "nope",
  "version": "0.0.1",
  "private": true,
  "author": "",
  "scripts": {
    "gen": "generate-it ./api_0.0.1.yml --yes --mocked --template https://github.com/acrontum/openapi-nodegen-typescript-server"
  },
  "dependencies": {
    "@types/node-fetch": "^2.5.10",
    "babel-polyfill": "^6.26.0",
    "body-parser": "^1.19.0",
    "celebrate": "^12.2.0",
    "command-line-args": "^5.1.1",
    "cors": "^2.8.5",
    "custom-error": "^0.2.1",
    "dotenv": "^8.6.0",
    "express": "^4.17.1",
    "express-auth-middle": "^1.1.2",
    "express-form-data": "^2.0.16",
    "generate-it-logger": "^1.2.4",
    "generate-it-mockers": "^1.0.6",
    "joi": "^17.3.0",
    "jsonwebtoken": "^8.5.1",
    "lodash": "^4.17.21",
    "morgan": "^1.10.0",
    "node-fetch": "^2.6.1",
    "node-worker-threads-pool": "^1.4.3",
    "object-reduce-by-map": "^2.0.2",
    "openapi-nodegen-config-helper": "^1.3.1",
    "recursive-readdir-sync": "^1.0.6",
    "request-ip": "^2.1.3",
    "swagger-ui-express": "^4.1.6",
    "tslib": "^2.2.0",
    "uuid": "^8.3.2",
    "winston": "^3.3.3",
    "worker-farm": "^1.7.0",
    "yamljs": "^0.3.0",
    "pg": "^8.6.0",
    "sequelize": "^6.6.4",
    "sequelize-cli": "^6.2.0"
  },
  "devDependencies": {
    "@types/body-parser": "^1.19.0",
    "@types/command-line-args": "^5.0.0",
    "@types/cors": "^2.8.10",
    "@types/express": "4.17.7",
    "@types/express-form-data": "^2.0.1",
    "@types/fs-extra": "^9.0.11",
    "@types/jest": "^26.0.23",
    "@types/jsonwebtoken": "^8.5.1",
    "@types/lodash": "^4.14.168",
    "@types/morgan": "^1.9.2",
    "@types/node": "^14.14.44",
    "@types/request-ip": "^0.0.35",
    "@types/supertest": "^2.0.11",
    "@types/swagger-ui-express": "^4.1.2",
    "@types/uuid": "^8.3.0",
    "@types/validator": "^13.1.3",
    "@types/yamljs": "^0.2.31",
    "@typescript-eslint/eslint-plugin": "^4.22.1",
    "@typescript-eslint/parser": "^4.22.1",
    "@zerollup/ts-transform-paths": "^1.7.18",
    "eslint": "^7.26.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^3.4.0",
    "generate-it": "^5.30.0",
    "generate-it-mockers": "^1.1.1",
    "jest": "^26.6.3",
    "nodemon": "^2.0.7",
    "prettier": "^2.3.2",
    "supertest": "^6.1.3",
    "ts-jest": "^26.5.6",
    "ts-node": "^9.1.1",
    "tsc-watch": "^4.4.0",
    "ttypescript": "^1.5.12",
    "typescript": "^4.2.4"
  },
  "mockingServer": true,
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+ssh://[email protected]/my/sweet/project.git"
  },
  "keywords": [],
  "license": "ISC",
  "bugs": {
    "url": "https://patco.com/my/sweet/project/issues"
  },
  "homepage": "https://patco.com/my/sweet/project#readme"
}

Expected behavior
Missing package listed in missing packages

Node & NPM version
v14.17.0
7.16.0

Operating system:
ubuntu 21.04

Additional context
Add any other context about the problem here.

[FEATURE] Add support for grouping by tag

Is your feature request related to a problem? Please describe.
Segement / path grouping is cool, but would be nice to add support for grouping by tag (first if multiple), since the structure of the swagger / routing may not reflect groupings of domain logic

Describe the solution you'd like
Add option which, when provided, overrides segment grouping and uses the tag item to group domains

Describe alternatives you've considered
Reorganizing the swagger

[BUG] Async API RabbitMQ | paramsOutputReducer does not return the correct schema structure

Describe the bug
The generated publish functions inside the RabbitMQService.ts file, are publishing messages with empty payloads since the objectReduceByMap call is not receiving (second argument) the correct schema structure that was defined in the async API file.
After looking into the source code of generate-it, I suspect reason being is that the provided async API file does not contain any http status.

To Reproduce
Steps to reproduce the behavior:

asyncapi: 2.0.0
info:
  title: rabbitmq_d
  version: 0.0.1
  description: rabbitmq asyncapi
  license:
    name: Apache 2.0
    url: 'https://www.apache.org/licenses/LICENSE-2.0'
defaultContentType: application/json
channels:
  /core/user-create:
    description: User has been created
    publish:
      operationId: coreUserCreatePublish
      message:
        contentType: application/json
        payload:
          $ref: '#/components/schemas/CoreUserCreate'
  /core/user-update:
    description: User has been created
    publish:
      operationId: coreUserUpdate
      message:
        contentType: application/json
        payload:
          $ref: '#/components/schemas/CoreUserUpdate'
components:
  schemas:
    CommonUserBaseModel:
      type: object
      properties:
        salutation:
          type: string
        firstName:
          type: string
        lastName:
          type: string
        email:
          type: string
        active:
          type: boolean
        deletedAt:
          type: string
        createdAt:
          type: string
        updatedAt:
          type: string
    CommonUserModel:
      allOf:
        - type: object
          properties:
            id:
              type: number
        - $ref: '#/components/schemas/CommonUserBaseModel'
    CoreUserCreate:
      type: object
      properties:
        user:
          $ref: '#/components/schemas/CommonUserModel'
    CoreUserUpdate:
      type: object
      properties:
        userId:
          type: number
        user:
          $ref: '#/components/schemas/CommonUserBaseModel'
  • see publishCoreUserCreatePublish function inside RabbitMQService.ts

Expected behavior
Generate-it should also accommodate async api files that do not contain http status numbers.
objectReduceByMap to receive in the second argument the correct schema structure that was defined in the async api file.

Node & NPM version
Node: 12.14.1
NPM: 6.14.8

Operating system:

  • OS: Windows 10 (WSL 2)
  • Version [e.g. 19.2]

[BUG] JwtAccess type is assumed but need to exist

Describe the bug
JwtAccess type is assumed to be defined. If not, the app cannot be built. The type is actually generated if there is a definition for it in the yml file.

To Reproduce
Steps to reproduce the behavior:
Run generate-it against a yml file which does not contain JwtAccess. eg:

 JwtAccess:
      type: object
      required:
        - id
      properties:
        id:
          type: number

Expected behavior
If there is no use of JWT Token, then generated files should not refer to it.

Node & NPM version
Node: 12.16.1
Npm 6.14.8

Operating system:

  • OS: Ubuntu
  • Version 18.4

[FEATURE] support null in templates

Is your feature request related to a problem? Please describe.
If i want to allow a string param to be validated with min length, but also allow null (to unset), I can't do that with the joi params

Describe the solution you'd like
with user/model.yml as:

type: object
properties:
  id:
    type: number
  username:
    required: true
    type: string
  email:
    minLength: 1
   pattern: maybe
    type: ['string', 'null']

then the generated joi validation should be something like this

usersUserIdPatch: {
    body: Joi.object({
      id: Joi.number(),
      username: Joi.string().allow(''),
      email: Joi.string().min(1).allow(null),
    }
  },

Describe alternatives you've considered
removing the min length param and validating in the domain - manually converting defined, empty string to null

Additional context
We could either do this in the swagger as above, or have a nullable flag somwhere (this may not be supported / standard)

The pathParamsToJoi function doesn't currently support array types as above - would have to update it to do some more checking

  public pathParamsToJoi (param: any, options: PathParamsToJoi): string {
    if (!param) {
      console.log(param, options);
      return;
    }
    const {paramTypeKey} = options;
    let validationText = param.name ? `'${param.name}'` + ':' : '';
    const isRequired = (options.requiredFields && options.requiredFields.includes(param.name)) || param.required;
    const type = param.type || param.schema.type;
    // for the email spec above: { name: 'email', minLength: 1, type: [ 'string', 'null' ] }
    // so this just results in "any" typings
    if (['string', 'number', 'integer', 'boolean'].includes(type)) {

[FEATURE] Domain control from path object

Is your feature request related to a problem? Please describe.
Would like tighter control of the domain naming and not only use the 1st segment of the path.

Describe the solution you'd like

x-domainName: UserManagement

[BUG] `req` parameter in Domain interface has type any

Describe the bug
req parameter has type any in methods of the Domain interfaces that take the request object.

This is a sample extract of a method in a Domain interface

authLogin(body: AuthPasswordResetPostBody, req: any): Promise<any>;

To Reproduce
Steps to reproduce the behavior:

  1. Write a post definition that includes x-passRequest

For example:
src/auth/login/post/

tags:
  - auth
summary: "Authenticates a user against provided credentials"
description: ""
operationId: authLogin
parameters:
  - in: body
    name: authLoginPostBody
    description: The users email
    schema:
      $ref: ../../../definitions/auth/login/post.yml
produces:
  - "application/json"
responses:
  "200":
    description: successful operation
    schema:
      $ref: ../../../definitions/auth/TokenUser.yml
  "401":
    description: Unauthenticated request
  "422":
    description: Unprocessable Entity
x-passRequest: true
  1. Generate api
  2. Open the AuthDomainInterface

Expected behavior
The authLogin method in the AuthDomainInterface should have the type NodegenRequest or Request from express.

Ask to auto install the dependencies

Discussed in #112

Originally posted by j-d-carmichael July 19, 2021
When there are dependency changes between the installed package.json file and the json file from the git repo of the tpl - the core will spit out the npm i command with all the new dep versions.

However.. you have to copy and paste them all in - would be cleaner if the core just asked then installed them.

Maybe an additional flag to opt into this functionality.. but maintaining dependency updates over a load of apis by hand is a pain in the arse!

@acrontum-sanchez @p-mcgowan

[BUG] Nested mixed required input output wrong joi

Describe the bug
Wrong joi validation output

To Reproduce
Steps to reproduce the behavior:
This nested object as an input model for post

type: object
required:
  - editable
properties:
  editable:
    type: object
    required:
      - text
    properties:
      channel:
        type: object
        required:
          - slug
          - name
        properties:
          slug:
            type: string
            description: The slug of the channel
          name:
            type: string
            description: The name of the channel
          isDefault:
            type: boolean
            description: Is this channel a default channel
      text:
        type: string
        description: The text of the item, this includes URL and user added text

Expected behavior
It should output:

  itemPost: {
    body: Joi.object({
      editable: Joi.object({
        channel: Joi.object({
          slug: Joi.string().allow('').required(),
          name: Joi.string().allow('').required(),
          isDefault: Joi.boolean(),
        }),
        text: Joi.string().allow('').required(),
      }).required(),
    }),
  },

It instead outputs:

  itemPost: {
    body: Joi.object({
      editable: Joi.object({
        channel: Joi.object({
          slug: Joi.string().allow(''),
          name: Joi.string().allow(''),
          isDefault: Joi.boolean(),
        }).required(),
        text: Joi.string().allow(''),
      }).required(),
    }),
  },

Note the actual output for body.editable which is correct, but the required elements within are incorrect

[FEATURE]

Problem:
Objects having null properties are not allowed by Joi

Description:
Consider we make a request with an object

user = {
 name: 'john',
 age: null
}

This does not pass Joi check since age is null.
This becomes a problem with some Angular features like form.reset() which resets values to null.
because the code generates Joi.string().allow('')
i think it should include null like Joi.string().allow('').allow(null)

related code is at SwaggerUtils.ts:

      if (type === 'string' && !isRequired && !param.minLength) {
        validationText += `.allow('')`;
      }

Swagger validations not added to the Joi validations.

Swagger validations are not being added to the Joi validations.

Example of swagger yml:

myVariable: in: query name: text required: true type: string minLength: 7 maxLength: 17
Result:

export default { customerGet: { query: { text: Joi.string() .allow("") .required() } } };

The min and max length validations are missing.

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.