Files
housesof/src/routes/index.ts
Félix Péault b7a857e2e6 🔥 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
2022-06-13 15:53:42 +02:00

58 lines
1.6 KiB
TypeScript

import type { RequestEvent, RequestHandlerOutput } from '@sveltejs/kit'
import { fetchAPI } from '$utils/api'
import { getRandomItems } from '$utils/functions'
export async function get({}: RequestEvent): Promise<RequestHandlerOutput> {
try {
// Get total of published photos
const totalRes = await fetchAPI(`
query {
photo (
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
location {
name
slug
country {
slug
name
flag { id }
}
}
image { id }
}
}
`)
const { data: { photo: photos }} = photosRes
if (photos) {
return {
body: {
photos,
}
}
}
} catch (error) {
return {
status: 404,
body: error,
}
}
}