Many years ago I worked with a 3rd party API that allowed you to search for a food item and would return the nutritional information for the given item. One quirk about this API is that if the search term matched a single item, a single object would be returned. But if the search term matched multiple items, an array of objects would be returned.
As an aside, I would recommend against designing your API (or your functions in general) this way. If a function or API endpoint can return multiple items, the return type should always be an array. If there is nothing to return, you return an empty array. If a single items is returned, you return an array with a single item. And if multiple items are returned, you return an array with all of the items. Always getting back an array, regardless of how many items are in the array, is much easier to work with than having to check if the data is an array or a single object.
This annoyance of not knowing if the data returned from the API was an object or an array of objects was compounded by the fact that we didn't take the proper steps to insulate our code base from this API. Let's take a look at some example code:
const foodItemOrItems: NutritionalInfo | NutritionalInfo[] = axios.get(`https://nutritional-info-api.com?search=${searchTerm}`);
if (Array.isArray(foodItemOrItems)) {
// do something with all food items
} else {
//l do something with single food items
}
By hitting the API directly where ever in the code base we needed to call it, we were forced to deal with the response object returned by the API. And this meant our code base was littered with code similar to the example above.
A Better Approach
Many years ago I worked with a 3rd party API that allowed you to search for a food item and would return the nutritional information for the given item. One quirk about this API is that if the search term matched a single item, a single object would be returned. But if the search term matched multiple items, an array of objects would be returned.
This annoyance of not knowing if the data returned from the API was an object or an array of objects was compounded by the fact that we didn't take the proper steps to insulate our code base from this API. Let's take a look at some example code:
By hitting the API directly where ever in the code base we needed to call it, we were forced to deal with the response object returned by the API. And this meant our code base was littered with code similar to the example above.
A Better Approach