0

I have created a base model class with is a model for the incoming data, I will be modeling the data inside of a class for some external reasons. Although I ran into a problem with is defining the incoming data into this model class.

This is my class

export class EntityBasic {
  constructor(
    public id: string,
    public title: string,
    public urn?: string,
    public risk_level?: string,
    public be_aware?: string,
    public body?: string,
    public published_at?: string,
    public created_at?: string,
    public updated_at?: string,
    public description?: string,
    public notes?: string,
  ) {}}
}

How I define the content inside of it in another page:

public getEntity(setEntity) {
    return new EntityBasic(
      setEntity.id,
      setEntity.title,
      setEntity?.urn,
      setEntity?.risk_level,
      setEntity?.be_aware,
      setEntity?.body,
      setEntity?.published_at,
      setEntity?.created_at,
      setEntity?.updated_at,
      setEntity?.report?.summary || '',
      setEntity?.report?.metadata?.source_notes,
      setEntity?.report?.metadata?.notes,
    );
  }

But defining the data like so, gave me problems, since some times there won't be a urn, or a risk_level for example, and the data will be messed up inside the class.
I would like a way to define like so (This didnt work):

public getEntity(setEntity) {
    return new EntityBasic(
      id = setEntity.id,
      title = setEntity.title,
      urn = setEntity?.urn,
      risk_level = setEntity?.risk_level,
    )
}
1
  • Can you not define a default value for each field? Or keep them null and overwrite this value in case there is a value from the incomming data. This way each field is atleast defined. Commented Nov 8, 2021 at 15:11

1 Answer 1

1

I believe wrap all parameters into one object is the best solution.

  1. Wrap them as interface
interface EntityBasicParameters {
    id: string;
    title: string;
    urn?: string;
    risk_level?: string;
    be_aware?: string;
    body?: string;
    published_at?: string;
    created_at?: string;
    updated_at?: string;
    description?: string;
    notes?: string;
}
  1. Accept only this object as constructor parameter
export class EntityBasic {
  constructor(params: EntityBasicParameters) {}}
}
  1. Now you can pass existent data only
public getEntity(setEntity) {
    return new EntityBasic({
      id: setEntity.id,
      title: setEntity.title,
      urn: setEntity?.urn,
      risk_level: setEntity?.risk_level,
    })
}

or just

public getEntity(setEntity) {
    return new EntityBasic(setEntity)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.