Fetch Object in combindation with swagger and Aurelia Validation

I would like to share some experience I made in the last days hoping this can help someone.

I’m using Swagger in combination with NSwagStudio to generate an api-bridge file, that works quite well. The only challange I had was, that fetching objects from api (e.g. for update), the fetched objects won’t get validated by aurelia validation.
Following my current setup:

My NSwag-Generated API bridge:

...
export class IMyClass implements IMyClasss{
    ... // Nothing to show because it's automatically generated
}
...

To apply the aurelia-validation I’m extending each model from that generated file:

import {MyClass as DtoMyClass} from '/apis/myapi-bridge-file';

export class MyClass extends DtoMyClass {}

ValidationRules
    .ensure((e : MyClass) => e.someField).required()
    .on(MyClass)

That setup works quite well for e.g. creating new Objects. For updating it didn’t work because fetching the object the validation rules didn’t get applied. All fields were populated well.

public LoadMyClass(id: number){
    this.myClassClient.Get(id)
        .then(myclass => {
            this.Myclass = myclass;
        });
}

After some research I found out that (of course) the class needs to get reinstanciated because the generated-code-class doesn’t know anything about validation rules.
Looking into the Swagger-generated class I saw, that the code always provides a constructor to recreate the object WITH validation rules. So, the solution for the challange was really easy:

public LoadMyClass(id: number){
    this.myClassClient.Get(id)
        .then(myclass => {
            this.MyClass = new MyClass(myclass); 
        });
}

And I’m so happy, that I didn’t need to create big and complex Mapping classes :slight_smile:

2 Likes

This might come in handy for my team, thanks!

2 Likes