Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to provide dynamic model type as parameter to @SerializableProperty()? #18

Open
krishnauppili opened this issue Dec 9, 2019 · 1 comment
Labels

Comments

@krishnauppili
Copy link

@serialize({})
export class SocialEntity extends Serializable{
@SerializeProperty({ map: 'entity_type' })
public entityType:string;

@SerializeProperty({
map: 'entity',
type:entityType == 'user'?UserProfile:entityType=='team'?TeamProfile:PageProfile
})
public entity:UserProfile | TeamProfile | PageProfile;
}

Something like this?

@krishnauppili krishnauppili changed the title Is it possible to provide dynamic model type as parameter to @Serializable property? Is it possible to provide dynamic model type as parameter to @SerializableProperty()? Dec 9, 2019
@delete
Copy link
Collaborator

delete commented Dec 21, 2019

Hi, I don't think so. But you could use a builder or factory.

Something like this:

Serialize({});
abstract class Profile extends Serializable {
  name: string
}

@Serialize({})
class UserProfile extends Profile {
  name: string = 'UserProfile'
}
@Serialize({})
class TeamProfile extends Profile {
  name: string = 'TeamProfile'
}
@Serialize({})
class PageProfile extends Profile {
  name: string = 'PageProfile'
}

enum PageType {
  USER = "user",
  TEAM = "team",
  PAGE = "page"
}

@Serialize({})
class SocialEntity extends Serializable {
  @SerializeProperty({
    map: "page_type"
  })
  pageType: PageType;

  @SerializeProperty({
    map: "page",
    type: Profile
  })
  page: Profile;
}

export class SocialEntityBuilder {
  build(data: Record<string, any>): SocialEntity {
    const social = new SocialEntity();
    social.deserialize(data);

    const pages = {
      [PageType.USER]: UserProfile,
      [PageType.TEAM]: TeamProfile,
      [PageType.PAGE]: PageProfile
    };

    social.page = new pages[social.pageType]();
    return social;
  }
}

const builder = new SocialEntityBuilder()

const social = builder.build({ page_type: 'user'});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants