Mapbox Search Nearby Companies - How to fetch more than 100 records?

We are trying to integrate the Mapbox Search Nearby Companies project, and we just realized it has a fatal flaw - it is only limited to 100 records, which will exclude a lot of nearby companies. Increasing the payload to a higher number will throw a 400 error. Is there any workaround to increase this limit?

Here is the function to search nearby companies:

const NearestCompanies = ({ context, runServerless, fetchProperties }) => {
 const [loading, setLoading] = useState(false);
 const [errorMessage, setErrorMessage] = useState(null);
 const [nearestCompaniesSorted, setNearestCompaniesSorted] = useState([]);
 const companiesToDisplay = 5;

 useEffect(() => {
 async function fetchCompaniesWithDistanceBatch() {
 setLoading(true);
 // Request companies batch from serverless function
 const companiesServerlessResponse = await runServerless({
 name: 'getCompaniesWithDistanceBatch',
 propertiesToSend: ['hs_object_id', 'city', 'state', 'address'],
 payload: { batchSize: 100 },
 });
 if (companiesServerlessResponse.status == 'SUCCESS') {
 const { companies } = companiesServerlessResponse.response;
 // Sort companies by distance
 setNearestCompaniesSorted(
 companies.sort((c1, c2) => c1.distance - c2.distance)
 );
 } else {
 setErrorMessage(companiesServerlessResponse.message);
 }
 setLoading(false);
 }
 fetchCompaniesWithDistanceBatch();
 }, [fetchProperties, runServerless]);

 if (errorMessage) {
 // If there's an error, show an alert
 return (
 <Alert title="Error executing serverless function" variant="error">
 {errorMessage}
 </Alert>
 );
 }
 if (loading) {
 // If loading, show a spinner
 return <LoadingSpinner />;
 }
 return (
 <Flex direction={'column'} gap={'lg'}>
 <Text variant="microcopy"> View the companies nearest to the currently displaying record.</Text>
 <CompaniesWithDistanceTable
 portalId={context.portal.id}
 companies={nearestCompaniesSorted.slice(0, companiesToDisplay)}
 propertiesToDisplay={[
 { title: 'Domain', propertyName: 'domain' },
 { title: 'Phone', propertyName: 'phone' },
 ]}
 />
 </Flex>
 );
};

Hi @ChrisSosa1337

Using an offset, you can retrieve more than through API. This requires an iterative statement, such as a do-while loop, to initiate a new array containing all records.

Thanks!

How would I add an offset? I search the entire world wide web and there are NO EXAMPLES using serverless functions.

Hi @ChrisSosa1337

Please share the code of the serverless function highlighted below screenshot:

“I hope this will help you out. Please mark it as Solution Accepted and upvote to help another Community member.
Thanks!”

Ok, it is in there. I think I found where to add it and I will test soon. I found an example on the Hubspot API call on how to fetch more than 100.

Ok, this is the method I have within getCompaniesWithDistanceBatch.js to make the HubSpot API call:

// Function to fetch companies batch using HubSpot API client
async function getOtherCompaniesBatch({
 hubspotClient,
 batchSize,
 }) {

 const getAllCompanies = async (offset, startingCompanies) => {
 // `console.log()` can be seen from Defer's dashboard
 console.log(`fetching contacts from offset: ${offset}`);

 const apiResponse = await hubspotClient.crm.companies.basicApi.getPage(
 batchSize,
 offset,
 PROPERTIES_TO_FETCH
 );

 const endingCompanies = startingCompanies.concat(apiResponse.results);

 if (apiResponse.paging) {
 return await getAllCompanies(
 apiResponse.paging.next.after,
 endingCompanies
 );
 } else {
 return endingCompanies

 };

 }
 const companies = await getAllCompanies(0, []);
 console.log(`fetched ${companies.length} companies`);

 return companies
 .map((company) => ({
 ...company,
 ...company.properties,
 }))
 .filter(
 // Exclude current company recored from list
 ({ hs_object_id }) => hs_object_id != currentCompany.hs_object_id
 );
}

For some reason this is timing out and returning nothing. Anything wrong here?

Ok, I used Copilot and it suggested this code, but I am getting timeout errors. Could you please help me out here?

// For HubSpot API calls
const hubspot = require('@hubspot/api-client');
// For obtaining geocoding data
const MapboxClient = require('@mapbox/mapbox-sdk/services/geocoding');
// For calculating the distance between two points
const turf = require('@turf/turf');

// To fetch needed company properties
const PROPERTIES_TO_FETCH = [
 'hs_object_id',
 'city',
 'state',
 'address',
 'domain',
 'phone',
 'name',
 'annualrevenue',
];

// Entry function of this module, it fetches batch of companies and calculates distance to the current company record
exports.main = async (context = {}) => {
 let currentCompany = await extendWithGeoCoordinates(context.propertiesToSend);
 if (!currentCompany.coordinates) {
 throw new Error(
 'Unable to calculate geo coordintes. Please specify an address for the record.'
 );
 }

 const { batchSize } = context.event.payload;
 let otherCompanies = await getOtherCompaniesBatch({
 hubspotClient: new hubspot.Client({
 accessToken: process.env['PRIVATE_APP_ACCESS_TOKEN'],
 }),
 batchSize,
 currentCompany,
 });

 // Extend companies records with geo coordinates and distance to the current company
 otherCompanies = await Promise.all(
 otherCompanies.map((company) => extendWithGeoCoordinates(company))
 );
 otherCompanies = await extendWithDistance({
 coordinatesFrom: currentCompany.coordinates,
 companies: otherCompanies.filter(({ coordinates }) => !!coordinates),
 });

 return {
 companies: otherCompanies,
 };
};

// Function to fetch companies batch using HubSpot API client
async function getOtherCompaniesBatch({
 hubspotClient,
 batchSize,
 currentCompany,
}) {
 let allCompanies = [];
 let offset = undefined; // Start from the first page

 do {
 const apiResponse = await hubspotClient.crm.companies.basicApi.getPage(
 batchSize,
 offset,
 PROPERTIES_TO_FETCH
 );

 allCompanies.push(...apiResponse.results);
 offset = apiResponse.paging?.next?.after;
 } while (offset);

 return allCompanies
 .filter(({ hs_object_id }) => hs_object_id !== currentCompany.hs_object_id)
 .map((company) => ({
 ...company,
 ...company.properties,
 }));
}

// Function to queery geo coordinates based on company address
async function extendWithGeoCoordinates(company) {
 try {
 return {
 ...company,
 coordinates: await getGeoCoordinates({
 address: buildFullAdress(company),
 }),
 };
 } catch (e) {
 return company;
 }
}

// Function to calculate the distance from current company record
async function extendWithDistance({ coordinatesFrom, companies }) {
 return Promise.all(
 companies.map(async (company) => {
 const distance = getDistance({
 coordinatesFrom,
 coordinatesTo: company.coordinates,
 });
 // Return existing company properties together with calculated distance
 return {
 ...company,
 distance,
 };
 })
 );
}

const buildFullAdress = ({ city, state, address }) => {
 return `${city} ${state} ${address}`;
};

// Function to obtain geographic coordinates for specified address
async function getGeoCoordinates({ address }) {
 // Use Mapbox Geocoding API
 // See https://docs.mapbox.com/api/search/geocoding/
 const mapboxClient = MapboxClient({
 accessToken: process.env.MAPBOX_ACCESS_TOKEN,
 });
 // Use JS SDK for working with Mapbox APIs: https://www.npmjs.com/package/@mapbox/mapbox-sdk
 const response = await mapboxClient.forwardGeocode({ query: address }).send();

 return response.body.features[0].geometry.coordinates;
}

// Function to calculate the distance between 2 points
function getDistance({ coordinatesFrom, coordinatesTo }) {
 // Use JS SDK for Turf project: https://www.npmjs.com/package/@turf/turf
 return turf.distance(turf.point(coordinatesFrom), turf.point(coordinatesTo), {
 units: 'miles',
 });
}

This is very important.