Manweill / swagger-axios-codegen

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

Creating objects with strong type validation #153 #179

Closed fairking closed 11 months ago

fairking commented 11 months ago

Solves #153

fairking commented 11 months ago

It needs some testing before merging it down to master. If someone could run it on the real life project and see what happens. I will do the same.

As an alternative we can introduce a static method, it will prevent breaking changes. But I feel the first approach is better, as it prevents developers from using not typed constructor:

export class LookupItemVm {
  'id'?: string;
  'name'?: string;
  'description'?: string;

  constructor(data: undefined | any = {}) {
    this['id'] = data['id'];
    this['name'] = data['name'];
    this['description'] = data['description'];
  }

  public static Create(data: LookupItemVm = {}) {
    return new LookupItemVm(data);
  }
}

Usage:

let item = LookupItemVm.Create({ id: 'abc', name: 'My ABC' });
fairking commented 11 months ago

Just tested on some bigger project. Looks ok so far.

Manweill commented 11 months ago

@fairking I don't have this usage scenario. You need more tests.

fairking commented 11 months ago

@fairking I don't have this usage scenario. You need more tests.

What do you mean? You don't use classes?

Manweill commented 11 months ago

@fairking I don't have this usage scenario. You need more tests.

What do you mean? You don't use classes?

Yeah, In my case , also use interface. so you should test the change more

Manweill commented 11 months ago

@fairking anything else to modify?

fairking commented 11 months ago

@fairking anything else to modify?

Nope, everything looks fine so far. I have tested my project and even found many bugs where wrong property names where passed to the constructor. I am happy with this approach and I could not find any issues.

playground

Also I checked NSwag and found out, they generate TS classes in the same way, so it is a sign others are doing the same approach.

fairking commented 11 months ago

Thanks @Manweill 👍