I am trying to convert an API Response into a totally different ViewModel, for multiple components.
a) One solution is to map/pipe the Data directly in the API proxy, however then API proxy is not very reusable, if I just want plain raw API Data.
b) This model-adapter pattern may not work, since in the example the adapter creates the same Data Object Type as API. https://florimond.dev/blog/articles/2018/09/consuming-apis-in-angular-the-model-adapter-pattern/ . Our data converter below, brings out totally different one.
Looking for any other good solutions.
Regular API:
export class ProductService {
private readonly apiUrl = environment.baseUrl + '/api/CalculateProducts/';
constructor(private httpClient: HttpClient) { }
getProductData(
productValuationDtoRequest: ProductValuationDtoRequest
): Observable<ProductValuationResponse> {
return this.httpClient.request<ProductValuationResponse>('post', this.apiUrl,
{body: productValuationDtoRequest}
);
}
}
Data Converter:
export class CalculateProductModelService {
constructor() { }
convertData(
productValuationResponse: ProductValuationResponse): CalculateCostModel {
const calculateProductModel: CalculateProductModel = {
valuationAttribute: productValuationResponse?.productValuationDetail[0]?.productValuationAttribute?.description,
livingAreaQuantity: productValuationResponse?.productValuationDetail[0]?.quantity,
livingAreaRate: productValuationResponse?.productValuationDetail[0]?.improvementUnitValue * 1.03,
livingAreaValue: productValuationResponse?.productValuationDetail[0]?.attributeTotalImprovementValue,
numberOfUnits: productValuationResponse?.numberOfUnits * 2,
replacementCostNew: productValuationResponse?.replacementCostNew,
goodPercentage: productValuationResponse?.percentageGood,
goodValue: productValuationResponse?.replacementCostNew * (100 - productValuationDto?.percentageGood) / 100,
total: productValuationResponse?.totalImprovementValue
};
return calculateProductModel;
}
from Angular: Convert API Data into New Data Type in Reusable/Clean Method
No comments:
Post a Comment