Manweill / swagger-axios-codegen

swagger client to use axios and typescript
MIT License
306 stars 83 forks source link

Support for 'required' Swagger keyword #106

Closed jkulcsar closed 4 years ago

jkulcsar commented 4 years ago

Hello, First of all thank you for this great library, been using it for a while in several projects. I came across today a situation where in theswagger.json file the requiredkeyword is used on one property but not the others, those being obviously optional. The generated data model should mark these optional with ? however it doesn't. For example:

      "MyRequestType": {
        "required": [
          "ArticleNumber"
        ],
        "type": "object",
        "properties": {
          "ArticleNumber": {
            "type": "string"
          },
          "ArticleDescription": {
            "type": "string"
          }
        }
      }

generates:

export class MyRequestType {
  /**  */
  'ArticleNumber': string;

  /**  */
  'ArticleDescription': string;

  constructor(data: undefined | any = {}) {
    this['ArticleNumber'] = data['ArticleNumber'];
    this['ArticleDescription'] = data['ArticleDescription'];
  }

  public static validationModel = {
    ArticleNumber: { required: true }
  };
}

From what I'm reading and seen with another generator, the property 'ArticleDescription': string; should be 'ArticleDescription'?: string; Is this perhaps configurable? I haven't seen any other configuration parameters that would help with this, currently I'm using

...
  generateValidationModel: true,
  strictNullChecks: true,
...

Thank you for your help or any suggestions.

Manweill commented 4 years ago

@jkulcsar this config is use on class model

fairking commented 4 years ago

Maybe apart from strictNullChecks: true the code must check if the type is nullable or not: https://github.com/Manweill/swagger-axios-codegen/blob/master/src/templates/template.ts

image

could be something like:

return `
  /** ${description || ''} */
  ${decorators}
  '${filedName}'${canNull || type.isNullable ? '?' : ''}:${type};
  `

However based on the answer from stackoverflow the ? character makes field optional, not nullable. So not nullable fields will require value assigned. It is configurable in typescript by the option strictNullChecks. https://stackoverflow.com/a/17220359/1143349

Or the not nullable property could be defined by required marker.

@jkulcsar The generated data model should mark these optional with ? however it doesn't.

I think it makes sense