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,
)
}
CodePudding user response:
I believe wrap all parameters into one object is the best solution.
- 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;
}
- Accept only this object as constructor parameter
export class EntityBasic {
constructor(params: EntityBasicParameters) {}}
}
- 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)
}