LabEG / Serializable

Small library for deserialization and serialization for javascript and typescript
MIT License
62 stars 10 forks source link

Nested properties #6

Closed SergeyMiracle closed 3 years ago

SergeyMiracle commented 3 years ago

Is it possible to use nested props?

For example:

  export default class RoleModel extends BaseModel {
  @jsonProperty(Number, null)
  public id: number | null = null

  @jsonProperty(String)
  public name = ''

  // Nested props 
  public relationships?: {
    @jsonProperty([PermissionModel])
    permissions: Array<PermissionModel> | undefined
  }
}
dellert commented 1 year ago

Hi, you can use this patch for recursive nested objects

diff --git a/node_modules/ts-serializable/dist/classes/Serializable.js b/node_modules/ts-serializable/dist/classes/Serializable.js
index 18231f3..24e3464 100644
--- a/node_modules/ts-serializable/dist/classes/Serializable.js
+++ b/node_modules/ts-serializable/dist/classes/Serializable.js
@@ -163,7 +163,11 @@ export class Serializable {
             Array.isArray(acceptedType) &&
                 Array.isArray(jsonValue)) {
                 if (acceptedType[0] === void 0) {
-                    this.onWrongType(prop, "invalid type", jsonValue);
+                    try {
+                        return jsonValue.map((arrayValue) => this.deserializeProperty(prop, [this.constructor, acceptedTypes[1] !== undefined ? acceptedTypes[1] : null], arrayValue, settings));
+                    } catch (e) {
+                        this.onWrongType(prop, "invalid type", jsonValue);
+                    }
                 }
                 return jsonValue.map((arrayValue) => this.deserializeProperty(prop, acceptedType, arrayValue, settings));
             }
LabEG commented 1 year ago

Nested properties work just like other properties.

import { jsonProperty, Serializable } from "ts-serializable";

export class Leg extends Serializable {
    @jsonProperty(String)
    public type: string = ''; // default value necessarily
}

export class User extends Serializable {
    @jsonProperty(Leg , null)
    public leftLeg: Leg | null = null; // default value necessarily
}