acr-lfr / generate-it Goto Github PK
View Code? Open in Web Editor NEWGenerate-It from yml files
Home Page: https://acr-lfr.github.io/generate-it/
License: MIT License
Generate-It from yml files
Home Page: https://acr-lfr.github.io/generate-it/
License: MIT License
I can not throw custom 422 errors.
I would like to be able to throw new http404();
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:
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:
Additional context
Add any other context about the problem here.
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:
Expected behavior
doesn't fail but git resets and tries again
Node & NPM version
14
Operating system:
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
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.
Describe the bug
When the swagger file does not contain any definition, the node generation fails.
To Reproduce
Steps to reproduce the behavior:
Expected behavior
The node app generation should not fail
Node & NPM version
node v10.17
Operating system:
Additional context
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" } } });
Currently the docs are a little sparse on the ground.
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[]; }
Describe the bug
Inline path params not working.
To Reproduce
Steps to reproduce the behavior:
generate:nodegen
scriptExpected behavior
Server should run
Node & NPM version
Node: 16.13.1
NPM: 8.1.2
Operating system:
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]
nodegen section is a bit slim right now - would be helpful to list and maintain all possible config options in 1 place, and a description of what they do.
It's a bit spread out now - the main page above has very little info and some of the options are only listed elsewhere in the sections which use them.
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:
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:
Additional context
Using OAS3
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.
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:
segmentFirstGrouping" 2
in .boatsrc
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:
Additional context
Add any other context about the problem here.
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"
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
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"
}
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:
Additional context
Add any other context about the problem here.
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:
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:
Additional context
Add any other context about the problem here.
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:
Expected behavior
That it generates without error.
Node & NPM version
12 lts latests npm
Operating system:
Describe the bug
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:
Additional context
Can't reproduce, running it again without making changes seems to work fine the second time
As the title says
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.
Create a new project - instal generate-it, add a script to generate the api... after running the script, all the content added at the beginning is lost..
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:
url?select=name,surname
Steps to reproduce converse behavior:
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.
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.
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
};
`
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:
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
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.
openapi-nodegen
informs the user they should manually update their package json file.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:
generate-ti
Expected behavior
The application rune without issue.
Node & NPM version
Node: 12.18.2
NPM: 6.14.8
Operating system:
Additional context
The error is fixed by just resaving the file.
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
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:
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.
Controlling the segments lookahead via the CLI is great,
But would be even nicer overriding it via the OpenAPI definition file for specific paths.
e.g. x-nodegen-lookahead
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.
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
I want to be able to generate a service class to communicate to another rest api, server to server.
Pretty much as the title says.
Managing the npm version number might get into a mess with multiple people allowing merges to master.
Following gitflow standards, should we keep the flow.. meaning all PRs should go to develop?
develop -> feature/{name} -> develop -> master
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'
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:
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:
The Joi calculation logic is not simple and therefore has never lived directly in the templates.
It should be possible to pull in helpers to templates as modules for the templates to use via the rc file.
Something like:
{
tplHelpers: ['https://github.com/acrontum/generate-it']
}
Describe the bug
The examples on the documentation on npm are not correct (https://www.npmjs.com/package/generate-it)
The node template should be -template https://github.com/acr-lfr/generate-it-typescript-server.git instead of --template https://github.com/acr-lfr/acr-lfr-typescript-server.git
Probably the async example is also incorrect.
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)) {
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
I can not throw custom 422 errors. Only through Joi.
I would like to be able to throw new http422(errors);
much the same as npm install dep from git tag or dependency.
This section needs expanding to be able to do so:
https://github.com/acrontum/openapi-nodegen/blob/master/lib/TemplateFetch.js#L94
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:
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
AuthDomainInterface
Expected behavior
The authLogin
method in the AuthDomainInterface
should have the type NodegenRequest
or Request
from express.
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!
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
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 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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.