Search code examples
javascriptjsonloopsrequesthierarchy

How to loop API calls for hierarchy until a condtion is true?


Im trying to figure out the "best" approach to make API calls loop until a condition is met (or if there is a better solutuon.)

The API will provide me with data regarding ultimateBeneficialOwners for a company. A company can have multiple owners that can be of type: corp or person.

my goal is to gather all information for each found owner, until i find owner(s) that is of type:person. then i know i found the top level of owner(s).

lets say i request all owners for company A.

const requestResult = await lookupOwners(cinForCompanyA);

Company A is owned by Company B so the response looks like this:

{
 owners: [
  {
   title: 'Company B',
   type: 'corp',
   cin: 1234,
  }
 ]
}

i store that data and now i want to request the data for CompanyB

const requestResult = await lookupOwners(1234);

and continue this process until the response object has type: 'person'. So lets say the lookup for Company B returns john and Anna as owners:

{
 owners: [
  {
   name: 'john',
   type: 'person',
  },
  {
   name: 'anna',
   type: 'person'
 ]
}

so to summarise: If the owners is type: corpi want to make a new api request for each corp until the response contains a accual person. Then we are done!

Im looking fo a approach that will work regardless if the inital company has 10 levels of owners or 0.

what is a good approach?

Hope this makes sense?

regards Casper


Solution

  • I think I would try to approach this with recursion, just putting each returned cin back into the function until it finds a person. You could also add checks depending on whether every company terminates in a person or if at some point you get a null value or what have you, depends on the specifics of the api you're querying.

    async function lookup(cin) {
      try {
        const company = await lookupOwners(cin);
        if (company.owners.find((o) => o.type === "person")) {
          return company;
        } else {
          return lookup(company?.owners[0].cin);
        }
      } catch (e) {
        return e;
      }
    }
    
    lookup(cin);