As I work on creating an API service for a carwash, I am faced with the challenge of handling a large and complex json object (referred to as the Carwash object). Each property within this object is essentially another object that consists of a mix of simple data types and additional custom objects that need to be instantiated. While examples for objects with fewer levels of properties utilizing the RxJs map function are plentiful, dealing with deeply nested objects like this presents a different set of hurdles.
Overview of Carwash.model.ts
export class Carwash {
public name: string;
public type: CARWASH_TYPE;
public rating: Rating;
public address: Address;
private _coordinates: CarwashCoordinates;
public promotions: Promotion[];
public silverPackage: Package;
public goldPackage: Package;
public platinumPackage: Package;
public exteriorPackage: Package;
public interiorPackage: Package;
public completePackage: Package;
public storeHours: StoreHours;
}
ApiService.ts
public static carwashUrl = 'http://localhost:4200/assets/data/carwash.json';
private static carwashObject: Carwash;
public name: string;
public type: CARWASH_TYPE;
public ratings: Rating[];
public address: Address;
private _coordinates: CarwashCoordinates;
public promotions: Promotion[];
public silverPackage: Package;
public goldPackage: Package;
public platinumPackage: Package;
public exteriorPackage: Package;
public interiorPackage: Package;
public completePackage: Package;
public storeHours: StoreHours;
constructor(private http: HttpClient) {
}
public getCarwash() {
console.log('getCarwash called');
if (!CarwashService.carwashObject) {
this.fetchCarwash().subscribe(
(carwash => CarwashService.carwashObject = carwash)
);
} else {
console.log('Carwash already fetched.');
}
}
private fetchCarwash(): Observable<Carwash> {
return this.http.get<any>(CarwashService.carwashUrl).pipe(
map(res => {
const carwashData = res.json();
this.name = carwashData.name; // Handling top level data is straightforward
this.type = carwashData.type; // Handling top level data is straightforward
for (const rating of carwashData.ratings) {
this.ratings.push(new Rating(rating.customerName,
rating.score,
rating.review,
rating.date)); // Handling top level data is straightforward
}
this.address = // Figuring out how to instantiate custom objects elegantly poses a challenge.
return new Carwash(this.name, this.type, etc...)
})
)
}
Is mapping the only way to navigate through this complexity? Could introducing helper functions help streamline the process of fetching the data? These are questions that linger in my mind.
NOTE: The specific structure of custom objects may not be crucial here. What matters is that they consist of basic data types along with other custom objects.