From b7a857e2e65f812758fb5fe62301cb82111645c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Mon, 13 Jun 2022 15:48:29 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20Get=2011=20random=20published=20?= =?UTF-8?q?photos=20on=20the=20Homepage=20collage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks to Directus help, this works! Concept: fetch all published photos IDs only, get 11 random items and query these 11 IDs Only 2 queries, one for the IDs and one for the photos --- src/routes/index.ts | 31 +++++++++++++++++++++++-------- src/utils/functions/index.ts | 9 +++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/routes/index.ts b/src/routes/index.ts index 652bf9f..ed34d16 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,15 +1,29 @@ import type { RequestEvent, RequestHandlerOutput } from '@sveltejs/kit' import { fetchAPI } from '$utils/api' +import { getRandomItems } from '$utils/functions' export async function get({}: RequestEvent): Promise { try { - const res = await fetchAPI(` + // Get total of published photos + const totalRes = await fetchAPI(` query { photo ( - limit: 11, - sort: ["-date_created"], filter: { status: { _eq: "published" }}, + limit: -1, ) { + id + } + } + `) + const { data: { photo: photosIds }} = totalRes + + // Get random photos + const randomPhotosIds = [...getRandomItems(photosIds, 11)].map(({ id }) => id) + + // Query these random photos from IDs + const photosRes = await fetchAPI(` + query { + photo (filter: { id: { _in: [${randomPhotosIds}] }}) { slug title city @@ -26,12 +40,13 @@ export async function get({}: RequestEvent): Promise { } } `) + const { data: { photo: photos }} = photosRes - const { data } = res - - return { - body: { - photos: data.photo + if (photos) { + return { + body: { + photos, + } } } } catch (error) { diff --git a/src/utils/functions/index.ts b/src/utils/functions/index.ts index 48781cf..49160ff 100644 --- a/src/utils/functions/index.ts +++ b/src/utils/functions/index.ts @@ -110,6 +110,15 @@ export const getRandomItem = (array: T[]): T => { } +/** + * Return random elements from an array + */ +export const getRandomItems = (array: any[], amount: number): T[] => { + const shuffled = Array.from(array).sort(() => 0.5 - Math.random()) + return shuffled.slice(0, amount) +} + + /** * Get a DOM element's position */