Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
insuusvenerati committed Oct 30, 2023
1 parent d236841 commit 2b027f5
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 4 deletions.
56 changes: 56 additions & 0 deletions src/lib/utils.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { env } from '$env/dynamic/private';
import type { Root } from './types/geographies';
import type { NominatimResponse } from './types/nominatim';
import type { WeatherResponse } from './types/weather';

export const getWeather = async ({ lat, lon }: { lat: string | number; lon: string | number }) => {
const url = `${env.API_URL}/forecast/${env.API_KEY}/${lat},${lon}?exclude=minutely`;
const geoUrl = `${env.GEO_URL}&x=${lon}&y=${lat}`;

try {
const [weather, location]: [WeatherResponse, Root] = await Promise.all([
fetch(url).then((res) => res.json()),
fetch(geoUrl).then((res) => res.json())
]);

return {
coords: { lat: Number(lat), lon: Number(lon) },
weather,
location: location.result.geographies['County Subdivisions'][0].BASENAME
};
} catch (error) {
console.error(error);
}
};

export const getZipcodeByCoords = async ({
lat,
lon,
fetch
}: {
lat: string | number;
lon: string | number;
fetch: typeof window.fetch;
}) => {
try {
const geoUrl = `${env.NOMINATIM_API_URL}&lon=${lon}&lat=${lat}`;

const locationResponse = await fetch(geoUrl, {
headers: {
'User-Agent': 'weather-app',
age: '31536000',
'cache-control': 'max-age=31536000'
}
});

if (!locationResponse.ok) {
throw new Error(locationResponse.statusText);
}

const location: NominatimResponse = await locationResponse.json();

return location.address.postcode;
} catch (error) {
console.error(`Failed to get zipcode for coordinates ${lat}, ${lon}: ${error}`);
}
};
2 changes: 1 addition & 1 deletion src/routes/weather/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from '../$types';
import { getZipcodeByCoords } from '$lib/util.server';
import { getZipcodeByCoords } from '$lib/utils.server';
import invariant from 'tiny-invariant';

export const load = (async ({ url, fetch, setHeaders }) => {
Expand Down
5 changes: 2 additions & 3 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { purgeCss } from 'vite-plugin-tailwind-purgecss';
import { defineConfig } from 'vitest/config';

export default defineConfig({
export default {
plugins: [sveltekit(), purgeCss()]
});
};

0 comments on commit 2b027f5

Please sign in to comment.