🤪 Process data to count photos per location and country

This commit is contained in:
2021-10-12 00:11:58 +02:00
parent dd0e820b83
commit 80747ffaf4

View File

@@ -29,6 +29,7 @@
const res = await fetchAPI(`
query {
locations: location (filter: { status: { _eq: "published" }}) {
id
name
slug
coordinates
@@ -48,6 +49,7 @@
}
countries: country (filter: { status: { _eq: "published" }}) {
id
name
slug
flag { id }
@@ -85,13 +87,17 @@
}
# Count
photo_aggregated {
countPhotos: photo_aggregated {
count { id }
}
location_aggregated {
countTotalPhotosByLocation: photo_aggregated (groupBy: "location") {
group
count { id }
}
country_aggregated {
countLocations: location_aggregated {
count { id }
}
countCountries: country_aggregated {
count { id }
}
}
@@ -100,7 +106,29 @@
const { data } = res
// Filter continents with linked countries
const filteredContinents = data.continent.filter((cont: any) => cont.countries.length)
const filteredContinents = data.continents.filter((cont: any) => cont.countries.length)
/**
* For each photos count, find the country and add the sum to it
*/
// Add count key
data.countries.forEach((country: any) => country.count = 0)
// Loop through totals by location
data.countTotalPhotosByLocation.forEach(({ group, count }: { group: { location: number }, count: { id: number }}) => {
const locationId = group.location
const photosCount = Number(count.id)
const countryIndex = data.countries.findIndex((country: any) => {
// Find the location of a country
return country.locations.find((location: any) => {
// Match the count location ID to the country location ID
return Number(location.id) === locationId
})
})
// Increment the count value found above
data.countries[countryIndex].count += photosCount
})
return {
props: {
@@ -109,9 +137,9 @@
continents: filteredContinents,
},
count: {
photos: data.photo_aggregated[0].count.id,
locations: data.location_aggregated[0].count.id,
countries: data.country_aggregated[0].count.id,
photos: data.countPhotos[0].count.id,
locations: data.countLocations[0].count.id,
countries: data.countCountries[0].count.id,
},
},
stuff: data,