Files
housesof/src/routes/[country]/[location]/[photo].ts

96 lines
2.9 KiB
TypeScript

import type { RequestEvent, RequestHandlerOutput } from '@sveltejs/kit'
import { fetchAPI } from '$utils/api'
export async function GET ({ params }: RequestEvent): Promise<RequestHandlerOutput> {
try {
// Get the first photo ID
const firstPhoto = await fetchAPI(`
query {
photo (search: "${params.photo}") {
id
}
}
`)
const firstPhotoId = firstPhoto?.data?.photo[0]?.id
// TODO: use same request for both queries (photo.id)
const photosBeforeFirst = await fetchAPI(`
query {
count: photo_aggregated (
filter: {
id: { _gt: ${firstPhotoId} },
location: { slug: { _eq: "${params.location}" }},
status: { _eq: "published" },
},
sort: "-id",
) {
count {
id
}
}
}
`)
// Define offset from the current count
const offset = Math.max(photosBeforeFirst?.data?.count[0]?.count.id - 5, 0)
const limit = 10
const res = await fetchAPI(`
query {
photos: photo (
filter: {
location: { slug: { _eq: "${params.location}" }}
status: { _eq: "published" },
},
sort: "-date_created",
limit: ${limit},
offset: ${offset},
) {
id
title
slug
date_taken
image {
id
title
width, height
}
city
}
location (filter: { slug: { _eq: "${params.location}" }}) {
id
name
slug
country {
name
slug
}
}
total_published: photo_aggregated (filter: { location: { slug: { _eq: "${params.location}" }}}) {
count { location }
}
}
`)
const { data } = res
const currentIndex = data.photos.findIndex((photo: any) => photo.slug === params.photo)
return {
body: {
photos: data.photos,
location: data.location[0],
currentIndex,
countPhotos: data.total_published[0].count.location,
limit,
offset,
}
}
} catch (error) {
return {
status: 404,
body: error,
}
}
}