For my current project, I am utilizing Vue with TypeScript and Axios to retrieve objects from the backend. Here is an example of the object type I am working with:
class Annoucement {
id!: string;
description?: string;
deal?: Deal;
realty?: Realty;
user?: User;
}
and the corresponding response structure:
{
"id": "guid",
"description": "string",
"deal": {
//...
},
"realty": {
//...
},
"user": {
//...
}
}
The challenge arises from the fact that the properties of deal
and reality
may vary, making it difficult to straightforwardly map them as follows:
let annoucement = new Annoucement();
annoucement.realty.floor = dto.realty.floor;
//...
UPDATE: Here are the class definitions:
class Deal {
private _id!: string;
private _dealInfo!: Sell | Rent;
public get id(): string {
return this._id;
}
public set id(value: string) {
this._id = value;
}
// more properties and methods...
}
// More class definitions for Sell, Rent, SellConditions, RentConditions, Realty, Office, CommercialBuilding, Building, etc.
Here is a class diagram illustrating the inheritance hierarchy
Given the variability in realty types when fetching announcements from the database, deciding on the best approach to map the response to an entity is challenging. Here are two possible solutions to address this issue:
- Inspect response properties with an
if
statement and define the type accordingly - Retrieve responses in separate functions where the response structure is known beforehand
While searching for a solution online, I found that most discussions revolve around mapping entities to DTOs, rather than dealing with this specific mapping dilemma.