Skip to content

Commit

Permalink
Add utility method to fetch all country locations
Browse files Browse the repository at this point in the history
  • Loading branch information
Pl217 committed Oct 3, 2023
1 parent e0eb870 commit 7d3405c
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions src/lib/data/locations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { Database } from '../../db';
import type { LocationId } from '../../db/models/location';
import type { PlanId } from '../../db/models/plan';
import type { InstanceOfModel } from '../../db/util/types';
import { getOrCreate } from '../../util';
import { NotFoundError } from '../../util/error';

export const getPlanCountries = async (
database: Database,
Expand All @@ -24,3 +28,55 @@ export const getPlanCountries = async (
},
});
};

export const getAllCountryLocations = async (
database: Database,
countryId: LocationId
): Promise<Map<number, InstanceOfModel<Database['location']>[]>> => {
const country = await database.location.findOne({
where: {
id: countryId,
adminLevel: 0,
status: 'active',
parentId: { [database.Op.IS_NULL]: true },
},
});

if (!country) {
throw new NotFoundError(
`No country with ID ${countryId}. ` +
`Make sure location with ID ${countryId} is an active country (i.e. admin 0 location)`
);
}

let previousAdminLevelIds = [country.id];
let nextAdminLevel = 1;
const countryLocationsByAdminLevel = new Map<
number,
Array<InstanceOfModel<Database['location']>>
>([[0, [country]]]);

while (previousAdminLevelIds.length) {
const locations = await database.location.find({
where: {
parentId: { [database.Op.IN]: previousAdminLevelIds },
adminLevel: nextAdminLevel,
status: 'active',
},
});

for (const location of locations) {
const countriesInAdminLevel = getOrCreate(
countryLocationsByAdminLevel,
nextAdminLevel,
() => []
);
countriesInAdminLevel.push(location);
}

previousAdminLevelIds = locations.map((l) => l.id);
nextAdminLevel++;
}

return countryLocationsByAdminLevel;
};

0 comments on commit 7d3405c

Please sign in to comment.