My objective is to save information in a backend server via POST requests. I need these requests to be executed one by one when the previous one finishes. But I need to add some logic between requests. These requests are made using RxJs Observables.
I'll give you some context. My app has 5 models: Country, State, City, Address, Person.
A Person has an Address, that belongs to a City, that belongs to a State, that belongs to a Country.
Each model contains its "parent" ID as foreign key (e.g. City has attribute 'state_id').
All the information is available via form. So when I submit the form, I want to save this information in my backend server.
In order to do this, I need to check (via GET request) if the country/state/city/address already exists in the database, if it does I need to bind its ID to the "child", otherwise I need to POST it and then bind its ID to the "child".
How can I achieve this? I have done some research and tried to do this piping concatMap()
operators. But my problem is: how can I concat
these requests?
This is what I have so far:
this.countrySvc.getCountryByName(countryAux.name).pipe(
concatMap(country1 => {
if (country1[0] != null){
/*Country exists in DB*/
countryAux.id = country1[0].id;
return of(country1[0]);
}
else{
/*Country is not in DB, i need to save it before continuing*/
this.countrySvc.postCountry(countryAux).pipe(
concatMap(country2 => {
countryAux.id = country2.id;
return of(country2);
})
)
.subscribe();
return of(countryAux);
}
}),
concatMap(country3 => {
console.log("Checking what do I get here: " + country3.name + " " + country3.id);
return country3;
})
)
.subscribe();
I can't figure out how to do this correctly. The sequence of requests I'm looking for is:
GET country // Search by name
if it exists
state.country_id = ID /*ID comes in response*/
else
POST country /*ID comes in response*/
state.country_id = ID
/*Once this (or these) previous request(s) complete*/
/*---------So far i have implemented up to here---------*/
GET province
if it exists
city.state_id = ID
else
POST state
city.state_id = ID
/*Once this (or these) previous request(s) complete*/
GET city
if it exists
address.city_id = ID
else
POST city
address.city_id = ID
/*Once this (or these) previous request(s) complete*/
GET address
if it exists
person.address_id = ID
else
POST address
person.address_id = ID
/*Once this (or these) previous request(s) complete*/
POST person
How can I manage to do that? Note that my main issue is that sometimes I will need to do some POST requests between some GET requests and sometimes I won't. However I'll need to return some Observable (with Country/State/City... data) in each situation to the next operator.