Skip to content

Support for subschema by using JSON Pointer ($id /$ref) #685

Open
@wupaz

Description

@wupaz

Hi,

A nice to have would be a support for pure JSON references.

I mean objects that are simply { $ref: 1 }.
https://json-schema.org/understanding-json-schema/structuring.html#using-id-with-ref

An example:

import { Component, VERSION } from "@angular/core";
import { Type, plainToClass } from "class-transformer";

export class A {
  public name: string;

  public id: number;
}

export class B {
  @Type(() => A)
  public prop1: A;

  @Type(() => A)
  public prop2: A;
}

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;

  ngOnInit(): void {
    const jsonStr: any = {
      $id: 1,
      prop1: {
        $id: 2,
        name: "test1",
        id: 100
      },
      prop2: {
        $id: 3,
        name: "test2",
        id: 101
      }
    };

    const jsonStrRef: any = {
      $id: 1,
      prop1: {
        $id: 2,
        name: "test1",
        id: 100
      },
      prop2: { $ref: 2 }
    };

    const res1 = plainToClass(B, jsonStr);
    console.log(res1);
    const res2 = plainToClass(B, jsonStrRef);
    console.log(res2);
  }
}

In this case, res1 is properly serialized. But for res2, prop1 is fine while prop2 is an empty object.

With a more complete example https://codesandbox.io/s/classtranformreftest-fr76o

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions