microsoft / kiota

OpenAPI based HTTP Client code generator
https://aka.ms/kiota/docs
MIT License
3.01k stars 210 forks source link

Introduce serialization functions dealing with model interface based objects. #1966

Closed nikithauc closed 1 year ago

nikithauc commented 2 years ago

The model classes contain the getFieldDeserializers and serialize(writer: SerializationWriter).

import {Entity} from './index';
import {Parsable, ParseNode, SerializationWriter} from '@microsoft/kiota-abstractions';

export class ModelX{
    public getFieldDeserializers() : Record<string, (node: ParseNode) => void> {
        return {...super.getFieldDeserializers(),
            "propA": n => { this.propA  = n.getCollectionOfPrimitiveValues<string>(); },
            "propB": n => { this.propB  = n.getStringValue(); },
            "propC": n => { this.propC = n.getDateValue(); },
        };
    };

    public serialize(writer: SerializationWriter) : void {
        if(!writer) throw new Error("writer cannot be undefined");
        super.serialize(writer);
        writer.writeCollectionOfPrimitiveValues<string>("propA", this.propA);
        writer.writeStringValue("propB", this.propB);
        writer.writeDateValue("propC", this.propC);
    };
}

After removing classes for this issue, the generation pattern would be something like:

interface Modelx{
 propA:string[],
 propB: string,
 propC: Date
}
function DeserializeToModelX( modelX:ModelX = {}) : Record<string, (node: ParseNode) => void> {
             return {  
              DeserializeToParent(modelX, node);
            "propA": n => { modelX.propA = n.getCollectionOfPrimitiveValues<string>(); },
            "propB": n => { modelX.propB= n.getStringValue(); },
            "propC": n => { modelX.propC = n.getDateValue(); },
        };
}

function SerializeModelX( modelX : ModelX , SerializationWriter) {
        super.serialize(writer);
        writer.writeCollectionOfPrimitiveValues<string>("propA", modelX.propA);
        writer.writeStringValue("propB", modelX.propB);
        writer.writeDateValue("propC", modelX.propC);

}

@baywet Is this what you have in mind?

baywet commented 2 years ago

Correct, the only detail is for serialization and inheritance, we'd need a similar change to the deserialization instead of super.