From 6e904850aa2daafedb76374810faf657d2dbd281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Tue, 16 Aug 2022 16:58:57 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20Migrate=20env=20variables=20to?= =?UTF-8?q?=20use=20internal=20SvelteKit=20system?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some API fetching function rewriting needed as privates cannot be included into public code --- src/components/molecules/Location.svelte | 3 +- src/routes/+layout.server.ts | 13 ++-- src/routes/+layout.svelte | 5 +- .../[country]/[location]/+page.server.ts | 3 +- src/routes/[country]/[location]/+page.svelte | 40 ++++++------ .../[country]/[location]/[photo]/+page.svelte | 45 +++++++------- src/routes/api/data/+server.ts | 23 +++++++ src/routes/api/newsletter/+server.ts | 5 +- src/routes/photos/+page.server.ts | 10 ++- src/routes/photos/+page.svelte | 62 ++++++++++--------- src/utils/api.ts | 11 ++-- src/utils/functions/swell.ts | 3 +- 12 files changed, 131 insertions(+), 92 deletions(-) create mode 100644 src/routes/api/data/+server.ts diff --git a/src/components/molecules/Location.svelte b/src/components/molecules/Location.svelte index ab6a8c0..a98832b 100644 --- a/src/components/molecules/Location.svelte +++ b/src/components/molecules/Location.svelte @@ -7,6 +7,7 @@ import { spring } from 'svelte/motion' import dayjs from 'dayjs' import { lerp } from '$utils/functions' + import { PUBLIC_PREVIEW_COUNT } from '$env/static/public' // Components import Image from '$components/atoms/Image.svelte' import Badge from '$components/atoms/Badge.svelte' @@ -48,7 +49,7 @@ })) // Change photo index from mouse position percentage - photoIndex = Math.round(lerp(0, Number(import.meta.env.VITE_PREVIEW_COUNT) - 1, moveProgress)) + photoIndex = Math.round(lerp(0, Number(PUBLIC_PREVIEW_COUNT) - 1, moveProgress)) } // Leaving mouseover diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 0991baf..f364612 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -1,6 +1,7 @@ import { error } from '@sveltejs/kit' import type { PageServerLoad } from './$types' import { fetchAPI } from '$utils/api' +import { PUBLIC_PREVIEW_COUNT } from '$env/static/public' export const load: PageServerLoad = async () => { @@ -21,7 +22,7 @@ export const load: PageServerLoad = async () => { date_updated photos ( sort: "-date_created", - limit: ${import.meta.env.VITE_PREVIEW_COUNT} + limit: ${PUBLIC_PREVIEW_COUNT} ) { image { id @@ -87,14 +88,14 @@ export const load: PageServerLoad = async () => { `) if (res) { - const { data } = res + const { data: { countPhotos, countLocations, countCountries, ...rest }} = res return { - ...data, + ...rest, count: { - photos: data.countPhotos[0].count.id, - locations: data.countLocations[0].count.id, - countries: data.countCountries[0].count.id, + photos: countPhotos[0].count.id, + locations: countLocations[0].count.id, + countries: countCountries[0].count.id, }, } } diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 20f2913..169dcdb 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -9,6 +9,7 @@ import { pageLoading, previousPage } from '$utils/stores' import { DURATION } from '$utils/contants' import '$utils/polyfills' + import { PUBLIC_ANALYTICS_KEY, PUBLIC_ANALYTICS_URL } from '$env/static/public' // Components import SVGSprite from '$components/SVGSprite.svelte' import SmoothScroll from '$components/SmoothScroll.svelte' @@ -84,7 +85,7 @@ {#if browser} {/if} \ No newline at end of file diff --git a/src/routes/[country]/[location]/+page.server.ts b/src/routes/[country]/[location]/+page.server.ts index 51dfb75..7a03331 100644 --- a/src/routes/[country]/[location]/+page.server.ts +++ b/src/routes/[country]/[location]/+page.server.ts @@ -1,5 +1,6 @@ import { error } from '@sveltejs/kit' import type { PageServerLoad } from './$types' +import { PUBLIC_LIST_AMOUNT } from '$env/static/public' import { fetchAPI } from '$utils/api' export const photoFields = ` @@ -56,7 +57,7 @@ export const load: PageServerLoad = async ({ params }) => { location: { slug: { _eq: "${slug}" }} }, sort: "-date_created", - limit: ${import.meta.env.VITE_LIST_AMOUNT}, + limit: ${PUBLIC_LIST_AMOUNT}, page: 1, ) { ${photoFields} diff --git a/src/routes/[country]/[location]/+page.svelte b/src/routes/[country]/[location]/+page.svelte index f1890be..55786ee 100644 --- a/src/routes/[country]/[location]/+page.svelte +++ b/src/routes/[country]/[location]/+page.svelte @@ -10,9 +10,10 @@ import dayjs from 'dayjs' import relativeTime from 'dayjs/plugin/relativeTime' import { quartOut } from '$animations/easings' - import { fetchAPI, getAssetUrlKey } from '$utils/api' + import { getAssetUrlKey } from '$utils/api' import { DELAY } from '$utils/contants' import { photoFields } from './+page.server' + import { PUBLIC_LIST_INCREMENT } from '$env/static/public' // Components import Metas from '$components/Metas.svelte' import PageTransition from '$components/PageTransition.svelte' @@ -61,7 +62,7 @@ photos = [...photos, ...newPhotos] // Define actions if the number of new photos is the expected ones - if (newPhotos.length === Number(import.meta.env.VITE_LIST_INCREMENT)) { + if (newPhotos.length === Number(PUBLIC_LIST_INCREMENT)) { // Increment the current page currentPage++ } @@ -71,24 +72,27 @@ } } - // [function] Load photos helper + // Load photos helper const loadPhotos = async (page?: number) => { - const res = fetchAPI(` - query { - photos: photo ( - filter: { - location: { slug: { _eq: "${params.location}" }}, - status: { _eq: "published" }, - }, - sort: "-date_created", - limit: ${import.meta.env.VITE_LIST_INCREMENT}, - page: ${page}, - ) { - ${photoFields} + const res = await fetch('/api/data', { + method: 'POST', + body: ` + query { + photos: photo ( + filter: { + location: { slug: { _eq: "${params.location}" }}, + status: { _eq: "published" }, + }, + sort: "-date_created", + limit: ${PUBLIC_LIST_INCREMENT}, + page: ${page}, + ) { + ${photoFields} + } } - } - `) - const { data: { photos }} = await res + `, + }) + const { data: { photos }} = await res.json() if (photos) { // Return new photos diff --git a/src/routes/[country]/[location]/[photo]/+page.svelte b/src/routes/[country]/[location]/[photo]/+page.svelte index b96ee2a..ed7e697 100644 --- a/src/routes/[country]/[location]/[photo]/+page.svelte +++ b/src/routes/[country]/[location]/[photo]/+page.svelte @@ -12,7 +12,7 @@ import { quartOut } from 'svelte/easing' import dayjs from 'dayjs' import { stagger, timeline } from 'motion' - import { fetchAPI, getAssetUrlKey } from '$utils/api' + import { getAssetUrlKey } from '$utils/api' import { previousPage } from '$utils/stores' import { DELAY } from '$utils/contants' import { throttle } from '$utils/functions' @@ -151,30 +151,33 @@ // Load new prev or next photos const isPrev = direction === directions.PREV - const res = await fetchAPI(` - query { - photos: photo ( - filter: { - location: { slug: { _eq: "${location.slug}" }}, - id: { _${isPrev ? 'gt' : 'lt'}: ${id} }, - status: { _eq: "published" }, - }, - sort: "${isPrev ? '' : '-'}id", - limit: ${limit}, - ) { - id - title - slug - date_taken - image { + const res = await fetch('/api/data', { + method: 'POST', + body: ` + query { + photos: photo ( + filter: { + location: { slug: { _eq: "${location.slug}" }}, + id: { _${isPrev ? 'gt' : 'lt'}: ${id} }, + status: { _eq: "published" }, + }, + sort: "${isPrev ? '' : '-'}id", + limit: ${limit}, + ) { id title + slug + date_taken + image { + id + title + } + city } - city } - } - `) - const { data: { photos: newPhotos }} = res + `, + }) + const { data: { photos: newPhotos }} = await res.json() // Not loading anymore isLoading = false diff --git a/src/routes/api/data/+server.ts b/src/routes/api/data/+server.ts new file mode 100644 index 0000000..4722449 --- /dev/null +++ b/src/routes/api/data/+server.ts @@ -0,0 +1,23 @@ +import { error } from '@sveltejs/kit' +import type { RequestHandler } from './$types' +import { fetchAPI } from '$utils/api' + + +export const POST: RequestHandler = async ({ request }) => { + try { + const body = await request.text() + + if (body) { + const req = await fetchAPI(body) + const res = await req + + if (res) { + return new Response(JSON.stringify({ + ...res + })) + } + } + } catch (err) { + throw error(500, err) + } +} \ No newline at end of file diff --git a/src/routes/api/newsletter/+server.ts b/src/routes/api/newsletter/+server.ts index c6cb5f0..9226410 100644 --- a/src/routes/api/newsletter/+server.ts +++ b/src/routes/api/newsletter/+server.ts @@ -1,5 +1,6 @@ import { error } from '@sveltejs/kit' import type { RequestHandler } from './$types' +import { NEWSLETTER_API_TOKEN, NEWSLETTER_LIST_ID } from '$env/static/private' export const POST: RequestHandler = async ({ request }) => { @@ -7,11 +8,11 @@ export const POST: RequestHandler = async ({ request }) => { const body = await request.text() if (body) { - const req = await fetch(`https://emailoctopus.com/api/1.6/lists/${import.meta.env.VITE_NEWSLETTER_LIST_ID}/contacts`, { + const req = await fetch(`https://emailoctopus.com/api/1.6/lists/${NEWSLETTER_LIST_ID}/contacts`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ - api_key: import.meta.env.VITE_NEWSLETTER_API_TOKEN, + api_key: NEWSLETTER_API_TOKEN, email_address: body, }) }) diff --git a/src/routes/photos/+page.server.ts b/src/routes/photos/+page.server.ts index 457c7da..3fd3765 100644 --- a/src/routes/photos/+page.server.ts +++ b/src/routes/photos/+page.server.ts @@ -1,16 +1,14 @@ import { error } from '@sveltejs/kit' import type { PageServerLoad } from './$types' import { fetchAPI } from '$utils/api' +import { PUBLIC_FILTERS_DEFAULT_COUNTRY, PUBLIC_FILTERS_DEFAULT_SORT, PUBLIC_GRID_AMOUNT } from '$env/static/public' -// Default filters values -const defaultCountry = String(import.meta.env.VITE_FILTERS_DEFAULT_COUNTRY) -const defaultSort = String(import.meta.env.VITE_FILTERS_DEFAULT_SORT) export const load: PageServerLoad = async ({ url }) => { try { // Query parameters - const queryCountry = url.searchParams.get('country') || defaultCountry - const querySort = url.searchParams.get('sort') || defaultSort + const queryCountry = url.searchParams.get('country') || PUBLIC_FILTERS_DEFAULT_COUNTRY + const querySort = url.searchParams.get('sort') || PUBLIC_FILTERS_DEFAULT_SORT // Query const res = await fetchAPI(` @@ -21,7 +19,7 @@ export const load: PageServerLoad = async ({ url }) => { status: { _eq: "published" }, }, sort: "${querySort === 'latest' ? '-' : ''}date_created", - limit: ${import.meta.env.VITE_GRID_AMOUNT}, + limit: ${PUBLIC_GRID_AMOUNT}, page: 1, ) { id diff --git a/src/routes/photos/+page.svelte b/src/routes/photos/+page.svelte index c28d238..7bbaa21 100644 --- a/src/routes/photos/+page.svelte +++ b/src/routes/photos/+page.svelte @@ -13,9 +13,9 @@ import relativeTime from 'dayjs/plugin/relativeTime' import { stagger, timeline } from 'motion' import { DELAY } from '$utils/contants' - import { fetchAPI } from '$utils/api' import { quartOut } from '$animations/easings' import { map, lerp, throttle } from '$utils/functions' + import { PUBLIC_FILTERS_DEFAULT_COUNTRY, PUBLIC_FILTERS_DEFAULT_SORT, PUBLIC_GRID_INCREMENT } from '$env/static/public' // Components import Metas from '$components/Metas.svelte' import PageTransition from '$components/PageTransition.svelte' @@ -57,8 +57,8 @@ /** * Filters */ - const defaultCountry: string = import.meta.env.VITE_FILTERS_DEFAULT_COUNTRY - const defaultSort: string = import.meta.env.VITE_FILTERS_DEFAULT_SORT + const defaultCountry: string = PUBLIC_FILTERS_DEFAULT_COUNTRY + const defaultSort: string = PUBLIC_FILTERS_DEFAULT_SORT const urlFiltersParams = new URLSearchParams() let filtered: boolean let filterCountry = $page.url.searchParams.get('country') || defaultCountry @@ -158,39 +158,43 @@ */ // [function] Load photos helper const loadPhotos = async (page: number) => { - const res = fetchAPI(` - query { - photos: photo ( - filter: { - ${filterCountry !== 'all' ? `location: { country: { slug: { _eq: "${filterCountry}" }} },` : ''} - status: { _eq: "published" }, - }, - sort: "${filterSort === 'latest' ? '-' : ''}date_created", - limit: ${import.meta.env.VITE_GRID_INCREMENT}, - page: ${page}, - ) { - id - title - slug - image { + const res = await fetch('/api/data', { + method: 'POST', + body: ` + query { + photos: photo ( + filter: { + ${filterCountry !== 'all' ? `location: { country: { slug: { _eq: "${filterCountry}" }} },` : ''} + status: { _eq: "published" }, + }, + sort: "${filterSort === 'latest' ? '-' : ''}date_created", + limit: ${PUBLIC_GRID_INCREMENT}, + page: ${page}, + ) { id title - } - location { slug - name - region - country { + image { + id + title + } + location { slug name - flag { id } + region + country { + slug + name + flag { id } + } } + city } - city } - } - `) - const { data: { photos }} = await res + `, + }) + + const { data: { photos }} = await res.json() if (photos) { // Return new photos @@ -209,7 +213,7 @@ photos = [...photos, ...newPhotos] // Define actions if the number of new photos is the expected ones - if (newPhotos.length === Number(import.meta.env.VITE_GRID_INCREMENT)) { + if (newPhotos.length === Number(PUBLIC_GRID_INCREMENT)) { // Increment the current page currentPage++ } diff --git a/src/utils/api.ts b/src/utils/api.ts index 7eea861..ab2104c 100644 --- a/src/utils/api.ts +++ b/src/utils/api.ts @@ -1,7 +1,8 @@ +import { env } from '$env/dynamic/private' +import { PUBLIC_API_URL_DEV, PUBLIC_API_URL_PROD, PUBLIC_API_GRAPHQL_PATH } from '$env/static/public' + // Define API URL from environment -export const API_URL = import.meta.env.DEV - ? `${import.meta.env.VITE_API_URL_DEV}` - : `${import.meta.env.VITE_API_URL_PROD}` +export const API_URL = env.DEV ? PUBLIC_API_URL_DEV : PUBLIC_API_URL_PROD /** @@ -9,7 +10,7 @@ export const API_URL = import.meta.env.DEV */ export const fetchAPI = async (query: string) => { try { - const res = await fetch(`${API_URL}${import.meta.env.VITE_API_GRAPHQL_PATH}`, { + const res = await fetch(`${API_URL}${PUBLIC_API_GRAPHQL_PATH}`, { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -25,7 +26,7 @@ export const fetchAPI = async (query: string) => { return data } } catch (error) { - console.error(error) + throw Error(error) } } diff --git a/src/utils/functions/swell.ts b/src/utils/functions/swell.ts index c644a94..837abc9 100644 --- a/src/utils/functions/swell.ts +++ b/src/utils/functions/swell.ts @@ -1,7 +1,8 @@ import swell from 'swell-node' +import { SWELL_API_TOKEN, SWELL_STORE_ID } from '$env/static/private' // Init Swell -swell.init(import.meta.env.VITE_SWELL_STORE_ID, import.meta.env.VITE_SWELL_API_TOKEN) +swell.init(SWELL_STORE_ID, SWELL_API_TOKEN)