I have an object of the following structure:
{
parent1: [
{childId: 1},
{childId: 2}
],
parent2: [
{childId: 3},
{childId: 4}
],
parent3: [
{childId: 5},
{childId: 6}
]
}
The following services:
addFamily(data: any): Observable<Family> {
const body = JSON.stringify(data);
return this.httpClient
.post<Family>(this.apiUrl + '/family', body, this.httpOptions)
}
addParent(data: any): Observable<Parent> {
const body = JSON.stringify(data);
return this.httpClient
.post<Parent>(this.apiUrl + '/parent', body, this.httpOptions)
}
addChild(data: any): Observable<Child> {
const body = JSON.stringify(data);
return this.httpClient
.post<Child>(this.apiUrl + '/child', body, this.httpOptions)
}
There are corresponding "family", "parent", and "child" tables in the database and I want to POST to each of these tables accordingly using RxJS higher order mapping operators to build a data response from prior calls. The idea is:
- call
addFamily()and return a newfamilyId - call
addParent()passing infamilyIdand returning a newparentId - call
addChild()passing inparentIdfor each child created
After performing the operations on the example object, there will be:
- 6 children added (FK child_parent)
- 3 parents added (FK parent_family)
- 1 family added
Currently the codebase is using multiple nested subscribes to perform the above tasks, which is why I looked into RxJS and stumbled upon the below code from a similar question.
private getData(): Observable<VmData> {
return this.service.getSomeData().pipe(
switchMap(session => this.service.getUserData(session.userId).pipe(
switchMap(user => this.service.getMetaData(user.id).pipe(
// by nesting, map has access to prior responses
map(userMeta => this.buildVmData(session, user, userMeta))
))
)),
tap(() => this.isLoading = false)
);
}
The above code would work if it was one family -> one parent -> one child, but how can I modify it to add 1 family, loop through each parent, and add each children under that parent? Any help is greatly appreciated. Thank you.