Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
2 changes: 2 additions & 0 deletions cspell.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ version: '0.2'
ignorePaths:
- node_modules
- bun.lockb
- package.json
- src/utils/get-formatted-weather-description.ts
- .tsbuildinfo
- .gitignore
- .next
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"@clerk/themes": "^2.1.36",
"@hookform/resolvers": "^3.9.0",
"@neondatabase/serverless": "^0.10.1",
"@nextui-org/react": "^2.6.11",
"@paralleldrive/cuid2": "^2.2.2",
"@radix-ui/colors": "^3.0.0",
"@radix-ui/react-checkbox": "^1.1.2",
Expand All @@ -73,9 +74,10 @@
"@react-email/components": "^0.0.25",
"@t3-oss/env-nextjs": "^0.11.1",
"@tanstack/react-query": "^5.59.15",
"@tanstack/react-query-next-experimental": "^5.71.10",
"@trpc/client": "next",
"@trpc/react-query": "next",
"@trpc/server": "next",
"@trpc/server": "^11.0.2",
"@upstash/redis": "^1.34.3",
"@vercel/analytics": "^1.3.1",
"@vercel/speed-insights": "^1.0.12",
Expand Down Expand Up @@ -105,7 +107,7 @@
"timeago.js": "^4.0.2",
"use-resize-observer": "^9.1.0",
"usehooks-ts": "^3.1.0",
"zod": "^3.23.8"
"zod": "^3.24.2"
},
"devDependencies": {
"@changesets/cli": "^2.27.9",
Expand Down
57 changes: 57 additions & 0 deletions src/app/(dashboard)/app/_components/weather.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use client';

import { type FC } from 'react';

import { useCoords } from '@/hooks/useCoords';
import { trpc } from '@/trpc/client';
import { getFormattedWeatherDescription } from '@/utils/get-formatted-weather-description';

import { Skeleton } from '@/primitives/skeleton';
import { formatDate } from '@/hooks/useDate';

export const WeatherData: FC = () => {
const coords = useCoords();
const { data: weatherData, isLoading } = trpc.weather.getWeatherData.useQuery(
{
latitude: coords?.latitude ?? 0,
longitude: coords?.longitude ?? 0,
},
{
enabled: !!coords,
retry: false,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
},
);

if (isLoading) {
return (
<div>
<Skeleton className="mt-2 w-[280] rounded-md">
<div className="h-4" />
</Skeleton>
<Skeleton className="mt-2 w-3/4 rounded-md">
<div className="h-4" />
</Skeleton>
</div>
);
}

return (
<div className="max-w-[280px] space-y-4">
<p className="text-base text-foreground-muted">Its</p>
<p className="text-base font-bold text-amber-500">
{formatDate(new Date())}
</p>

{weatherData && (
<p className=" cursor-default text-left text-sm leading-5 text-foreground-muted">
You can expect a 👆 high of {weatherData.temp_max.toFixed()}º and a 👇
low of {weatherData.temp_min.toFixed()}º{' '}
{getFormattedWeatherDescription(weatherData.summary)}.
</p>
)}
</div>
);
};
7 changes: 5 additions & 2 deletions src/app/(dashboard)/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import { api } from '@/lib/trpc/server';
import { RecentModules } from './_components/recent-modules';
import { WelcomeMessage } from './_components/welcome-message';
import { WeatherData } from './_components/weather';

export default async function DashboardHome() {
const modules = await api.modules.getUserModules();

return (
<div className="flex flex-1 gap-6">
<div className="flex flex-1 flex-col gap-6 md:flex-row">
<div className="flex-1">
<WelcomeMessage />
<RecentModules modules={modules.slice(0, 4)} />
</div>
<div className="min-w-[280px] rounded-lg border p-4">Right side</div>
<div className="min-w-[280px] rounded-lg border p-4">
<WeatherData />
</div>
</div>
);
}
18 changes: 18 additions & 0 deletions src/hooks/useCoords.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use client';

import { useEffect, useState } from 'react';

export const useCoords = () => {
const [coords, setCoords] = useState<{
latitude: number;
longitude: number;
} | null>(null);

useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
setCoords(position.coords);
});
}, []);

return coords;
};
20 changes: 20 additions & 0 deletions src/hooks/useDate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export const formatDate = (date: Date) => {
// Get day of week, day, month and year
const dayOfWeek = date.toLocaleDateString('en-US', { weekday: 'long' });
const day = date.getDate();
const month = date.toLocaleDateString('en-US', { month: 'long' });
const year = date.getFullYear();

// Add ordinal suffix to day
let suffix = 'th';
if (day % 10 === 1 && day !== 11) {
suffix = 'st';
} else if (day % 10 === 2 && day !== 12) {
suffix = 'nd';
} else if (day % 10 === 3 && day !== 13) {
suffix = 'rd';
}

// Format as "Saturday, the 5th of April 2025"
return `${dayOfWeek}, the ${day.toString()}${suffix} of ${month} ${year.toString()}`;
};
2 changes: 2 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { earlyAccessRouter } from './routers/early-access';
import { modulesRouter } from './routers/modules';
import { weatherRouter } from './routers/weather';
import { createCallerFactory, createRouter, publicProcedure } from './trpc';

export const appRouter = createRouter({
healthcheck: publicProcedure.query(() => 'ok'),
earlyAccess: earlyAccessRouter,
modules: modulesRouter,
weather: weatherRouter,
});

export type AppRouter = typeof appRouter;
Expand Down
125 changes: 125 additions & 0 deletions src/server/routers/weather.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { createRouter, protectedProcedure } from '../trpc';

const hours = z
.object({
summary: z.object({
symbol_code: z.string(),
}),
})
.optional();

const timeseriesSchema = z.array(
z.object({
time: z.string(),
data: z.object({
next_12_hours: hours,
next_6_hours: hours,
next_1_hours: hours,
instant: z.object({
details: z.object({
air_temperature: z.number(),
}),
}),
}),
}),
);

const weatherDataSchema = z.object({
temp_max: z.number(),
temp_min: z.number(),
summary: z.string().optional(),
});

const input = z.object({
latitude: z.number(),
longitude: z.number(),
});

const getCurrentWeatherData = async ({
latitude,
longitude,
}: z.infer<typeof input>) => {
const date = new Date().toISOString().slice(0, 10);
const response = await fetch(
`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${latitude.toString()}&lon=${longitude.toString()}`,
{
headers: {
'User-Agent': `noodle.run (https://github.com/noodle-run/noodle)`,
},
},
);

const data = (await response.json()) as {
properties: { timeseries: unknown };
};

const timeseries = timeseriesSchema
.parse(data.properties.timeseries as z.infer<typeof timeseriesSchema>)
.filter((one) => one.time.includes(date));

const temperatures = timeseries.map(
(t) => t.data.instant.details.air_temperature,
);

let summary;
if (timeseries[0]) {
const { next_12_hours, next_6_hours, next_1_hours } = timeseries[0].data;
const nextData = next_12_hours ?? next_6_hours ?? next_1_hours;
summary = nextData?.summary.symbol_code;
}

const weatherData = {
summary,
temp_max: Math.max(...temperatures),
temp_min: Math.min(...temperatures),
};

return weatherDataSchema.parse(weatherData);
};

export const weatherRouter = createRouter({
getWeatherData: protectedProcedure
.input(input)
.output(weatherDataSchema)
.query(async ({ input, ctx }) => {
const date = new Date().toISOString().slice(0, 10);
const cacheKey = `weather:${date}:${ctx.user.id}`;

if (typeof ctx.redis !== 'undefined' && typeof ctx.redis !== 'string') {
try {
const cachedWeatherData = await ctx.redis.get(cacheKey);

if (!cachedWeatherData) {
const weatherData = await getCurrentWeatherData(input);
const secondsUntilMidnight = Math.round(
(new Date().setHours(24, 0, 0, 0) - Date.now()) / 1000,
);

await ctx.redis.set(cacheKey, JSON.stringify(weatherData), {
ex: secondsUntilMidnight,
});
return weatherData;
}
return weatherDataSchema.parse(cachedWeatherData);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to fetch cached weather data',
});
}
}

try {
return await getCurrentWeatherData(input);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to fetch weather data',
});
}
}),
});
48 changes: 48 additions & 0 deletions src/trpc/client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// src/trpc/react.tsx
'use client';

import type { AppRouter } from '@/server/index';
import { getBaseUrl } from '@/utils/base-url';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental';
import { httpBatchLink } from '@trpc/client';
import { createTRPCReact } from '@trpc/react-query';
import { type inferRouterOutputs } from '@trpc/server';
import { useState } from 'react';
import SuperJSON from 'superjson';

export const trpc = createTRPCReact<AppRouter>();

export function TRPCReactProvider(props: {
children: React.ReactNode;
headers: Headers;
}) {
const [queryClient] = useState(() => new QueryClient());

const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: getBaseUrl() + '/api/trpc',
headers() {
const headers = new Map(props.headers);
return Object.fromEntries(headers);
},
transformer: SuperJSON,
}),
],
}),
);

return (
<QueryClientProvider client={queryClient}>
<ReactQueryStreamedHydration transformer={SuperJSON}>
<trpc.Provider client={trpcClient} queryClient={queryClient}>
{props.children}
</trpc.Provider>
</ReactQueryStreamedHydration>
</QueryClientProvider>
);
}

export type RouterOutputs = inferRouterOutputs<AppRouter>;
Loading