Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Moved to tRPCs fetch API #184

Merged
merged 16 commits into from
Feb 1, 2024
Merged
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ UPSTASH_RATELIMITER_EXCLUDED_IPS="..." // List of IPs separated by comma
RESEND_API_KEY="re_..."
QWEATHER_API_KEY="..."
API_NINJA_API_KEY="..."
NEXT_PUBLIC_CONVEX_URL="https://..."
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@ After that you can run the following command, to look at the current state (with

We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary.

If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help.
If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://discord.gg/VUv9vAHyjW) and ask for help.

- [Next.js](https://nextjs.org)
- [Tailwind CSS](https://tailwindcss.com)
- [tRPC](https://trpc.io)
- [TypeScript](https://www.typescriptlang.org)
- [Turborepo](https://turbo.build/repo)
- [Playwright](https://playwright.dev)
- [Convex](https://convex.dev)
#### APIs
- [OpenWeatherMap API](https://openweathermap.org/api)
- [Open Meteo API](https://open-meteo.com)
Expand Down
2 changes: 1 addition & 1 deletion apps/web/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const config = withMyBundleAnalyzer(withPWA(
reactStrictMode: true,

/** Enables hot reloading for local packages without a build step */
transpilePackages: ['@weatherio/api', '@weatherio/ui', '@weatherio/types'],
transpilePackages: ['@weatherio/api', '@weatherio/ui', '@weatherio/types', '@weatherio/city-data'],
i18n
}))
)
Expand Down
2 changes: 2 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@
"@vercel/analytics": "^1.1.2",
"@vercel/speed-insights": "^1.0.9",
"@weatherio/api": "workspace:^0.1.0",
"@weatherio/city-data": "workspace:^0.1.0",
"@weatherio/types": "workspace:^0.1.0",
"@weatherio/ui": "workspace:^0.1.0",
"classnames": "^2.5.1",
"convex": "^1.8.0",
"dayjs": "^1.11.10",
"next": "^14.1.0",
"next-axiom": "^1.1.1",
Expand Down
14 changes: 14 additions & 0 deletions apps/web/src/components/ConvexClientProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { ReactNode } from "react";
import { ConvexProvider, ConvexReactClient } from "convex/react";

import { env } from "~/env.mjs";

const convex = new ConvexReactClient(env.NEXT_PUBLIC_CONVEX_URL);

export default function ConvexClientProvider({
children,
}: {
children: ReactNode;
}) {
return <ConvexProvider client={convex}>{children}</ConvexProvider>;
}
6 changes: 5 additions & 1 deletion apps/web/src/env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ export const env = createEnv({
.transform((v) => (v ? `https://${v}` : undefined)),
PORT: z.coerce.number().default(3000)
},
client: {
NEXT_PUBLIC_CONVEX_URL: z.string().min(1)
},
/**
* Destructure all variables from `process.env` to make sure they aren't tree-shaken away.
*/
runtimeEnv: {
PORT: process.env.PORT,
VERCEL_URL: process.env.VERCEL_URL
VERCEL_URL: process.env.VERCEL_URL,
NEXT_PUBLIC_CONVEX_URL: process.env.NEXT_PUBLIC_CONVEX_URL

// NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
},
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/lib/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const api = createTRPCNext<AppRouter>({
(opts.direction === "down" && opts.result instanceof Error),
}),
httpBatchLink({
url: `${getBaseUrl()}/api`,
url: `${getBaseUrl()}/api/trpc`,
}),
],
};
Expand Down
5 changes: 3 additions & 2 deletions apps/web/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { appWithTranslation } from "next-i18next";

import { Toaster } from "@weatherio/ui/sonner";

import ConvexClientProvider from "~/components/ConvexClientProvider";
import { PWALifeCycle } from "~/components/PWALifecycle";
import { api } from "~/lib/utils/api";

Expand All @@ -21,7 +22,7 @@ const inter = Inter({ subsets: ["latin-ext"] });

const MyApp: AppType = ({ Component, pageProps }) => {
return (
<>
<ConvexClientProvider>
<Head>
<meta
name="google-site-verification"
Expand All @@ -40,7 +41,7 @@ const MyApp: AppType = ({ Component, pageProps }) => {
<SpeedInsights />
<AxiomWebVitals />
<ReactQueryDevtools initialIsOpen={false} />
</>
</ConvexClientProvider>
);
};

Expand Down
19 changes: 0 additions & 19 deletions apps/web/src/pages/api/[trpc].ts

This file was deleted.

26 changes: 26 additions & 0 deletions apps/web/src/pages/api/trpc/[trpc].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { NextRequest } from "next/server";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";

import { appRouter, createTRPCContext } from "@weatherio/api";

import { env } from "~/env.mjs";

export const config = { runtime: "edge" };

// export API handler
export default async function handler(req: NextRequest) {
return fetchRequestHandler({
endpoint: "/api/trpc",
router: appRouter,
req,
createContext: createTRPCContext,
onError:
env.NODE_ENV === "development"
? ({ path, error }) => {
console.error(
`❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`,
);
}
: undefined,
});
}
101 changes: 68 additions & 33 deletions apps/web/src/pages/locationsettings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@ import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { observer } from "@legendapp/state/react";
import cn from "classnames";
import { useQuery } from "convex/react";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { RxCross2 } from "react-icons/rx";
import { ClipLoader } from "react-spinners";
import { toast } from "sonner";

import type { ICity } from "@weatherio/types";
import { api as convexApi } from "@weatherio/city-data";

import search2Image from "~/assets/search2.png";
import Layout from "~/components/Layout";
import { api } from "~/lib/utils/api";
import { api as tRPCApi } from "~/lib/utils/api";
import { activeCity$, addedCities$ } from "~/states";

const LocationSettings = observer(() => {
Expand All @@ -34,23 +36,20 @@ const LocationSettings = observer(() => {
const { t: translationLocationSettings } = useTranslation("locationsettings");
const { t: translationCommon } = useTranslation("common");

const { data: findCitiesByNameData = [], status: findCitiesByNameStatus } =
api.search.findCitiesByName.useQuery({
name: searchValue.name,
});
/*
Fetches on every change in the search Value the cities that match the search value
*/

const { data: findCityByIdData = [], status: findCityByIdStatus } =
api.search.findCityById.useQuery({
id: searchValue.id,
});
const findCitiesByName = useQuery(convexApi.getCity.findCitiesByName, {
name: searchValue.name,
});

const { data: findCityByNameData = [], status: findCityByNameStatus } =
api.search.findCityByName.useQuery({
name: searchValue.name,
});
const findCityById = useQuery(convexApi.getCity.findCityById, {
id: searchValue.id,
});

const findCityByCoordinatesMutation =
api.reverseGeoRouter.getCity.useMutation({
tRPCApi.reverseGeoRouter.getCity.useMutation({
onSuccess: (data) => {
if (data) {
setSearchValue(data);
Expand All @@ -65,9 +64,24 @@ const LocationSettings = observer(() => {
setResults([]);
return;
}
if (!findCitiesByNameData || findCitiesByNameStatus !== "success") return;
setResults(findCitiesByNameData);
}, [searchValue, findCitiesByNameData, findCitiesByNameStatus]);
if (findCitiesByName === undefined) return;
setResults(() => {
const cities: ICity[] = [];
findCitiesByName.map((city) => {
cities.push({
id: city.id,
name: city.name,
country: city.country,
region: city.region,
coord: {
lon: city.coord.lon,
lat: city.coord.lat,
},
});
});
return cities;
});
}, [searchValue, findCitiesByName]);

const removeCityFromAddedCities = (city: ICity) => {
if (addedCities$.get().length === 1) {
Expand All @@ -92,10 +106,7 @@ const LocationSettings = observer(() => {
lat: 0,
},
};
if (
searchValue.id.toString().length === 15 ||
searchValue.id.toString().length === 14
) {
if (searchValue.id.toString().length > 15) {
city = {
id: searchValue.id,
name: searchValue.name,
Expand All @@ -108,34 +119,58 @@ const LocationSettings = observer(() => {
};
} else {
if (searchValue.id !== 0 && searchValue.country !== "") {
if (findCityByIdStatus === "loading") {
if (findCityById === undefined) {
toast.loading(translationLocationSettings("try again toast"));
return;
}
if (!Array.isArray(findCityByIdData)) {
city = findCityByIdData.city;
if (findCityById) {
city = {
id: findCityById.id,
name: findCityById.name,
country: findCityById.country,
region: findCityById.region,
coord: {
lon: findCityById.coord.lon,
lat: findCityById.coord.lat,
},
};
} else {
console.log("city not found by id reverse geocoding");
toast.error(translationLocationSettings("city not found toast"));
return;
}
} else {
if (findCityByNameStatus === "loading") {
toast.loading(translationLocationSettings("try again toast"));
return;
}
if (!Array.isArray(findCityByNameData)) {
city = findCityByNameData.city;
if (findCitiesByName?.[0]) {
city = {
id: findCitiesByName[0].id,
name: findCitiesByName[0].name,
country: findCitiesByName[0].country,
region: findCitiesByName[0].region,
coord: {
lon: findCitiesByName[0].coord.lon,
lat: findCitiesByName[0].coord.lat,
},
};
} else {
console.log("city not found by name reverse geocoding");
toast.error(translationLocationSettings("city not found toast"));
return;
}
}
}

if (city) {
// Checks if the city is already added, and if it is a reverse geocoded city.
// If it is not a reverse geocoded city, we can compare by id,
// but if it is a reverse geocoded city, we have to compare by name.
const existingCity = addedCities$
.get()
.find((value: ICity) => value.name === city!.name);
.find(
(value: ICity) =>
value.name === city!.name &&
(value.id.toString().length > 15 ||
city!.id.toString().length > 15),
);
if (addedCities$.get().find((value: ICity) => value.id === city!.id)) {
activeCity$.set(city);
toast.success(translationLocationSettings("switched to city toast"));
Expand Down Expand Up @@ -188,7 +223,7 @@ const LocationSettings = observer(() => {
"w-full border-b-2 border-black bg-[#d8d5db] pb-0.5 pl-3 pt-0.5 text-xl font-bold text-black outline-none",
{
"pr-10":
findCitiesByNameStatus === "loading" &&
findCitiesByName === undefined &&
inputRef.current?.value &&
inputRef.current?.value.length > 0,
},
Expand Down Expand Up @@ -221,7 +256,7 @@ const LocationSettings = observer(() => {
}}
/>
<div className="absolute right-3 top-1/2 mt-0.5 -translate-y-1/2">
{findCitiesByNameStatus === "loading" &&
{findCitiesByName === undefined &&
inputRef.current?.value &&
inputRef.current?.value.length > 0 ? (
<ClipLoader color={"#ffffff"} loading={true} size={20} />
Expand Down
Loading
Loading