From 80747ffaf44b5d2840e7b87ae656b153c3a94b8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Tue, 12 Oct 2021 00:11:58 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=A4=AA=20Process=20data=20to=20count=20ph?= =?UTF-8?q?otos=20per=20location=20and=20country?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/routes/__layout.svelte | 42 +++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/src/routes/__layout.svelte b/src/routes/__layout.svelte index 20eff12..35f336f 100644 --- a/src/routes/__layout.svelte +++ b/src/routes/__layout.svelte @@ -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,