🔥 Get 11 random published photos on the Homepage collage
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
This commit is contained in:
@@ -1,15 +1,29 @@
|
|||||||
import type { RequestEvent, RequestHandlerOutput } from '@sveltejs/kit'
|
import type { RequestEvent, RequestHandlerOutput } from '@sveltejs/kit'
|
||||||
import { fetchAPI } from '$utils/api'
|
import { fetchAPI } from '$utils/api'
|
||||||
|
import { getRandomItems } from '$utils/functions'
|
||||||
|
|
||||||
export async function get({}: RequestEvent): Promise<RequestHandlerOutput> {
|
export async function get({}: RequestEvent): Promise<RequestHandlerOutput> {
|
||||||
try {
|
try {
|
||||||
const res = await fetchAPI(`
|
// Get total of published photos
|
||||||
|
const totalRes = await fetchAPI(`
|
||||||
query {
|
query {
|
||||||
photo (
|
photo (
|
||||||
limit: 11,
|
|
||||||
sort: ["-date_created"],
|
|
||||||
filter: { status: { _eq: "published" }},
|
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
|
slug
|
||||||
title
|
title
|
||||||
city
|
city
|
||||||
@@ -26,12 +40,13 @@ export async function get({}: RequestEvent): Promise<RequestHandlerOutput> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
`)
|
`)
|
||||||
|
const { data: { photo: photos }} = photosRes
|
||||||
|
|
||||||
const { data } = res
|
if (photos) {
|
||||||
|
|
||||||
return {
|
return {
|
||||||
body: {
|
body: {
|
||||||
photos: data.photo
|
photos,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -110,6 +110,15 @@ export const getRandomItem = <T extends unknown> (array: T[]): T => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return random elements from an array
|
||||||
|
*/
|
||||||
|
export const getRandomItems = <T extends unknown> (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
|
* Get a DOM element's position
|
||||||
*/
|
*/
|
||||||
|
|||||||
Reference in New Issue
Block a user