Move from TRPC to server actions

This commit is contained in:
Timothy Armes
2024-04-08 09:48:18 +02:00
parent cd83db2385
commit 0540ecc05a
25 changed files with 1802 additions and 1774 deletions
@@ -17,8 +17,8 @@ import { SwitchField } from "@/components/form/SwitchField";
import { TextAreaField } from "@/components/form/TextAreaField";
import { TextField } from "@/components/form/TextField";
import { addTournamentSchema } from "@/schemas";
import { addTournament } from "@/server/addTournament";
import { TimeControl } from "@/types";
import { trpc } from "@/utils/trpc";
type TournamentFormValues = z.infer<typeof addTournamentSchema>;
@@ -30,7 +30,7 @@ const Map = dynamic(() => import("./Map"), {
const TournamentForm = () => {
const t = useTranslations("AddTournament");
const at = useTranslations("App");
const addTournament = trpc.addTournament.useMutation();
const [responseMessage, setResponseMessage] = useState({
isSuccessful: false,
message: "",
@@ -48,7 +48,7 @@ const TournamentForm = () => {
const onSubmit = async (data: TournamentFormValues) => {
try {
await addTournament.mutateAsync(data);
await addTournament(data);
setResponseMessage({
isSuccessful: true,
message: t("success"),
@@ -12,14 +12,13 @@ import { clearMessage } from "@/components/InfoMessage";
import { TextAreaField } from "@/components/form/TextAreaField";
import { TextField } from "@/components/form/TextField";
import { contactUsSchema } from "@/schemas";
import { trpc } from "@/utils/trpc";
import { contactUs } from "@/server/contactUs";
type TournamentFormValues = z.infer<typeof contactUsSchema>;
const ContactForm = () => {
const t = useTranslations("Contact");
const contactUs = trpc.contactUs.useMutation();
const [responseMessage, setResponseMessage] = useState({
isSuccessful: false,
message: "",
@@ -31,7 +30,7 @@ const ContactForm = () => {
const onSubmit = async (data: TournamentFormValues) => {
try {
await contactUs.mutateAsync(data);
await contactUs(data);
setResponseMessage({
isSuccessful: true,
message: t("success"),
@@ -4,8 +4,8 @@ import { last } from "lodash";
import { useTranslations } from "next-intl";
import { twMerge } from "tailwind-merge";
import { TournamentResultsData } from "@/server/fetchTournamentResults";
import { getNewRating } from "@/utils/eloCalculator";
import { TournamentResultsData } from "@/utils/trpc";
type TournamentResultsProps = {
results: TournamentResultsData;
+15 -17
View File
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useMemo } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query";
import { isEmpty, sortBy } from "lodash";
import { useTranslations } from "next-intl";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
@@ -13,8 +14,8 @@ import { Spinner } from "@/components/Spinner";
import { SelectField } from "@/components/form/SelectField";
import { TournamentSelectField } from "@/components/form/TournamentSelectField";
import { fetchTournamentResultsSchema } from "@/schemas";
import { fetchTournamentResults } from "@/server/fetchTournamentResults";
import { Link } from "@/utils/navigation";
import { trpc } from "@/utils/trpc";
import { KFactor } from "./KFactor";
import { ManualEloForm } from "./ManualEloForm";
@@ -55,21 +56,18 @@ export default function Elo() {
data: allResults,
isFetching,
error,
} = trpc.fetchTournamentResults.useQuery(
{
id: tournamentId?.trim(),
},
{
refetchOnWindowFocus: false,
staleTime: Infinity,
cacheTime: 10 * 60 * 1000,
enabled: hasTournamentId,
retry: false,
},
);
} = useQuery({
queryKey: ["fetchTournamentResults", { id: tournamentId?.trim() }],
queryFn: async () => fetchTournamentResults({ id: tournamentId?.trim() }),
refetchOnWindowFocus: false,
staleTime: Infinity,
gcTime: 10 * 60 * 1000,
enabled: hasTournamentId,
retry: false,
});
const playerOptions = sortBy(
(allResults ?? []).map((player) => ({
(allResults?.data ?? []).map((player) => ({
value: player.id,
label: player.name,
})),
@@ -173,7 +171,7 @@ export default function Elo() {
console.error(error);
}
const playerResults = allResults?.find((p) => p.id === player);
const playerResults = allResults?.data?.find((p) => p.id === player);
return (
<section className="grid place-items-center bg-white pb-20 dark:bg-gray-800">
@@ -215,7 +213,7 @@ export default function Elo() {
</div>
)}
{error && (
{error instanceof Error && (
<div className="mt-8 text-center text-error">
{error.message.startsWith("ERR_")
? t(error.message as TranslationKey)
@@ -269,7 +267,7 @@ export default function Elo() {
<TournamentResults
playerId={player}
kFactor={parseInt(kFactor)}
results={allResults ?? []}
results={allResults?.data ?? []}
/>
)}
-21
View File
@@ -1,21 +0,0 @@
import {
FetchCreateContextFnOptions,
fetchRequestHandler,
} from "@trpc/server/adapters/fetch";
import { appRouter } from "@/server/appRouter";
const handler = (request: Request) => {
return fetchRequestHandler({
endpoint: "/api/trpc",
req: request,
router: appRouter,
createContext: function (
opts: FetchCreateContextFnOptions,
): object | Promise<object> {
return {};
},
});
};
export { handler as GET, handler as POST };
@@ -2,7 +2,11 @@ import { useTranslations } from "next-intl";
import { FieldPath, FieldValues } from "react-hook-form";
import { TimeControlColours } from "@/constants";
import { SearchedTournament, trpc } from "@/utils/trpc";
import { getTournamentDetails } from "@/server/getTournamentDetails";
import {
SearchedTournament,
searchTournaments,
} from "@/server/searchTournaments";
import { AsyncSelectField, AsyncSelectFieldProps } from "./AsyncSelectField";
@@ -27,10 +31,9 @@ export const TournamentSelectField = <
...rest
}: TournamentSelectFieldProps<TFieldValues, TFieldName>) => {
const at = useTranslations("App");
const client = trpc.useContext();
const loadOption = async (ffeId: string) => {
const tournament = await client.getTournamentDetails.fetch({ ffeId });
const { data: tournament } = await getTournamentDetails({ ffeId });
return !tournament
? undefined
@@ -42,7 +45,7 @@ export const TournamentSelectField = <
};
const loadOptions = async (searchValue?: string) => {
const tournaments = await client.searchTournaments.fetch({
const { data: tournaments } = await searchTournaments({
searchValue: searchValue ?? "",
});
-45
View File
@@ -1,45 +0,0 @@
import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { getFetch, httpBatchLink, loggerLink } from "@trpc/client";
import superjson from "superjson";
import { trpc } from "@/utils/trpc";
export const TrpcProvider = ({ children }: { children: React.ReactNode }) => {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: { queries: { staleTime: 5000 } },
}),
);
const url = "/api/trpc";
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
loggerLink({
enabled: () => true,
}),
httpBatchLink({
url,
fetch: async (input, init?) => {
const fetch = getFetch();
return fetch(input, {
...init,
credentials: "include",
});
},
}),
],
transformer: superjson,
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</trpc.Provider>
);
};
+4 -3
View File
@@ -1,16 +1,17 @@
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Provider } from "jotai";
import { useDynamicViewportUnits } from "@/hooks/useDynamicViewportUnits";
import { TrpcProvider } from "./TrpcProvider";
export default function Providers({ children }: { children: React.ReactNode }) {
const queryClient = new QueryClient();
useDynamicViewportUnits();
return (
<Provider>
<TrpcProvider>{children}</TrpcProvider>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</Provider>
);
}
+79
View File
@@ -0,0 +1,79 @@
"use server";
import { format } from "date-fns";
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { addTournamentSchema } from "@/schemas";
import { TournamentData } from "@/types";
import { TimeControl } from "@/types";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
const tcMap: Record<TimeControl, TournamentData["time_control"]> = {
[TimeControl.Classic]: "Cadence Lente",
[TimeControl.Rapid]: "Rapide",
[TimeControl.Blitz]: "Blitz",
[TimeControl.Other]: "Other",
};
export const addTournament = action(addTournamentSchema, async (input) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB").collection("tournaments");
const { name, email, message, tournament } = input;
const tournamentData: Omit<TournamentData, "_id" | "tournament_id"> = {
...tournament,
date: format(tournament.date, "dd/MM/yyyy"),
start_date: format(tournament.date, "dd/MM/yyyy"),
end_date: format(tournament.date, "dd/MM/yyyy"),
time_control: tcMap[tournament.time_control],
coordinates: tournament.coordinates as [number, number],
entry_method: "manual",
pending: true,
status: "scheduled",
};
const result = await db.insertOne(tournamentData);
if (result.insertedId) {
const { tournament, country, date, time_control } = tournamentData;
if (typeof process.env.DISCORD_WEBHOOK_ADD_TOURNAMENT_URL === "string") {
await fetch(process.env.DISCORD_WEBHOOK_ADD_TOURNAMENT_URL as string, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
embeds: [
{
title: "Tournament Submitted",
fields: [
{ name: "Tournament", value: tournament },
{ name: "Country", value: country },
{ name: "Date", value: date },
{
name: "Time Control",
value: time_control,
},
{ name: "Sender", value: name },
{ name: "Sender Email", value: email },
{ name: "Message", value: message ?? "" },
],
},
],
}),
});
}
return true;
}
} catch (error) {
errorLog(error);
throw error;
}
});
-16
View File
@@ -1,16 +0,0 @@
import { addTournament } from "./procedures/addTournament";
import { contactUs } from "./procedures/contactUs";
import { fetchTournamentResults } from "./procedures/fetchTournamentResults";
import { getTournamentDetails } from "./procedures/getTournamentDetails";
import { searchTournaments } from "./procedures/searchTournaments";
import { router } from "./trpc";
export const appRouter = router({
contactUs,
addTournament,
searchTournaments,
getTournamentDetails,
fetchTournamentResults,
});
export type AppRouter = typeof appRouter;
+36
View File
@@ -0,0 +1,36 @@
"use server";
import { z } from "zod";
import { contactUsSchema } from "@/schemas";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
export const contactUs = action(contactUsSchema, async (input) => {
try {
const { email, subject, message } = input;
await fetch(process.env.DISCORD_WEBHOOK_CONTACT_URL as string, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
embeds: [
{
title: "Contact",
fields: [
{ name: "Email", value: email },
{ name: "Subject", value: subject },
{ name: "Message", value: message },
],
},
],
}),
});
return true;
} catch (error) {
errorLog(error);
throw error;
}
});
@@ -1,9 +1,11 @@
"use server";
import { z } from "zod";
import { fetchTournamentResultsSchema } from "@/schemas";
import { errorLog } from "@/utils/logger";
import { publicProcedure } from "../trpc";
import { action } from "./safeAction";
const dbSchema = z.array(
z.object({
@@ -43,6 +45,8 @@ const outputSchema = z.array(
}),
);
export type TournamentResultsData = z.infer<typeof outputSchema>;
const getEloDetails = (elo: string | null) => {
if (elo === null || elo === "") {
return { elo: 0, estimated: false, national: false };
@@ -102,10 +106,9 @@ const reportFetchError = async (url: string, error: any) => {
}
};
export const fetchTournamentResults = publicProcedure
.input(fetchTournamentResultsSchema)
.output(outputSchema)
.query(async ({ input }) => {
export const fetchTournamentResults = action(
fetchTournamentResultsSchema,
async (input) => {
try {
const headers = new Headers();
const apiKey = process.env.RESULTS_API_KEY;
@@ -114,8 +117,6 @@ export const fetchTournamentResults = publicProcedure
headers.append("api-key", apiKey);
}
console.log(input.id);
const rawResults = await fetch(
`${process.env.RESULTS_SCRAPER_URL}${input.id}`,
{
@@ -130,8 +131,8 @@ export const fetchTournamentResults = publicProcedure
}
const parsedResults = dbSchema.parse(results);
return parsedResults.map<z.infer<typeof outputSchema>[number]>(
(player) => ({
return outputSchema.parse(
parsedResults.map<z.infer<typeof outputSchema>[number]>((player) => ({
id: player.id,
name: player.name,
...getEloDetails(player.elo),
@@ -140,17 +141,18 @@ export const fetchTournamentResults = publicProcedure
result.colour === "B"
? "white"
: result.colour === "N"
? "black"
: "",
? "black"
: "",
opponent: result.opponent_name,
...getResultDetails(result),
...getEloDetails(result.opponent_elo),
})),
}),
})),
);
} catch (error) {
reportFetchError(input.id, error);
errorLog(JSON.stringify(error, null, 2));
throw error;
}
});
},
);
+45
View File
@@ -0,0 +1,45 @@
"use server";
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { TournamentData } from "@/types";
import { TimeControl, tcMap } from "@/types";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
const inputSchema = z.object({
ffeId: z.string(),
});
export const getTournamentDetails = action(inputSchema, async (input) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB");
const t = await db
.collection("tournaments")
.findOne<TournamentData>({ tournament_id: input.ffeId });
if (t === null) {
return null;
}
const timeControl = tcMap[t.time_control] ?? TimeControl.Other;
return {
id: t._id.toString(),
ffeId: t.tournament_id,
tournament: t.tournament,
town: t.town,
department: t.department,
date: t.date,
url: t.url,
timeControl,
status: t.status,
};
} catch (error) {
errorLog(JSON.stringify(error, null, 2));
throw error;
}
});
-83
View File
@@ -1,83 +0,0 @@
import { format } from "date-fns";
import clientPromise from "@/lib/mongodb";
import { addTournamentSchema } from "@/schemas";
import { TournamentData } from "@/types";
import { TimeControl } from "@/types";
import { errorLog } from "@/utils/logger";
import { publicProcedure } from "../trpc";
const tcMap: Record<TimeControl, TournamentData["time_control"]> = {
[TimeControl.Classic]: "Cadence Lente",
[TimeControl.Rapid]: "Rapide",
[TimeControl.Blitz]: "Blitz",
[TimeControl.Other]: "Other",
};
export const addTournament = publicProcedure
.input(addTournamentSchema)
.mutation(async ({ input }) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB").collection("tournaments");
const { name, email, message, tournament } = input;
const tournamentData: Omit<TournamentData, "_id" | "tournament_id"> = {
...tournament,
date: format(tournament.date, "dd/MM/yyyy"),
start_date: format(tournament.date, "dd/MM/yyyy"),
end_date: format(tournament.date, "dd/MM/yyyy"),
time_control: tcMap[tournament.time_control],
coordinates: tournament.coordinates as [number, number],
entry_method: "manual",
pending: true,
status: "scheduled",
};
const result = await db.insertOne(tournamentData);
if (result.insertedId) {
const { tournament, country, date, time_control } = tournamentData;
if (
typeof process.env.DISCORD_WEBHOOK_ADD_TOURNAMENT_URL === "string"
) {
await fetch(
process.env.DISCORD_WEBHOOK_ADD_TOURNAMENT_URL as string,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
embeds: [
{
title: "Tournament Submitted",
fields: [
{ name: "Tournament", value: tournament },
{ name: "Country", value: country },
{ name: "Date", value: date },
{
name: "Time Control",
value: time_control,
},
{ name: "Sender", value: name },
{ name: "Sender Email", value: email },
{ name: "Message", value: message ?? "" },
],
},
],
}),
},
);
}
return true;
}
} catch (error) {
errorLog(error);
throw error;
}
});
-34
View File
@@ -1,34 +0,0 @@
import { contactUsSchema } from "@/schemas";
import { errorLog } from "@/utils/logger";
import { publicProcedure } from "../trpc";
export const contactUs = publicProcedure
.input(contactUsSchema)
.mutation(async ({ input }) => {
try {
const { email, subject, message } = input;
await fetch(process.env.DISCORD_WEBHOOK_CONTACT_URL as string, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
embeds: [
{
title: "Contact",
fields: [
{ name: "Email", value: email },
{ name: "Subject", value: subject },
{ name: "Message", value: message },
],
},
],
}),
});
return true
} catch (error) {
errorLog(error);
throw error;
}
});
@@ -1,45 +0,0 @@
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { TournamentData } from "@/types";
import { TimeControl, tcMap } from "@/types";
import { errorLog } from "@/utils/logger";
import { publicProcedure } from "../trpc";
const inputSchema = z.object({
ffeId: z.string(),
});
export const getTournamentDetails = publicProcedure
.input(inputSchema)
.query(async ({ input }) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB");
const t = await db
.collection("tournaments")
.findOne<TournamentData>({ tournament_id: input.ffeId });
if (t === null) {
return null;
}
const timeControl = tcMap[t.time_control] ?? TimeControl.Other;
return {
id: t._id.toString(),
ffeId: t.tournament_id,
tournament: t.tournament,
town: t.town,
department: t.department,
date: t.date,
url: t.url,
timeControl,
status: t.status,
};
} catch (error) {
errorLog(JSON.stringify(error, null, 2));
throw error;
}
});
@@ -1,96 +0,0 @@
import { endOfDay } from "date-fns";
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { TournamentData } from "@/types";
import { TimeControl, Tournament, tcMap } from "@/types";
import { errorLog } from "@/utils/logger";
import { removeDiacritics } from "@/utils/string";
import { publicProcedure } from "../trpc";
const inputSchema = z.object({
searchValue: z.string(),
limit: z.number().optional(),
});
type SearchedTournament = Pick<
Tournament,
| "id"
| "ffeId"
| "date"
| "department"
| "status"
| "timeControl"
| "tournament"
| "town"
| "url"
>;
export const searchTournaments = publicProcedure
.input(inputSchema)
.query(async ({ input }) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB");
const searchTerms = input.searchValue
.split(" ")
.map((s) => removeDiacritics(s.trim()))
.filter((s) => s !== "")
.map((s) => ({ tournament_index: { $regex: s, $options: "i" } }));
const data = await db
.collection("tournaments")
.aggregate<TournamentData>([
{
$addFields: {
dateParts: {
$dateFromString: {
dateString: "$start_date",
format: "%d/%m/%Y",
},
},
},
},
{
$match: {
$and: [
{ federation: { $eq: "FFE" } },
{ dateParts: { $lte: endOfDay(new Date()) } },
...searchTerms,
],
},
},
{
$sort: {
dateParts: -1,
},
},
{ $limit: input.limit ?? 20 },
{
$unset: "dateParts",
},
])
.toArray();
return data.map<SearchedTournament>((t) => {
const timeControl = tcMap[t.time_control] ?? TimeControl.Other;
return {
id: t._id.toString(),
ffeId: t.tournament_id,
tournament: t.tournament,
town: t.town,
department: t.department,
date: t.start_date,
url: t.url,
timeControl,
status: t.status,
};
});
} catch (error) {
errorLog(JSON.stringify(error, null, 2));
throw error;
}
});
+3
View File
@@ -0,0 +1,3 @@
import { createSafeActionClient } from "next-safe-action";
export const action = createSafeActionClient();
+97
View File
@@ -0,0 +1,97 @@
"use server";
import { endOfDay } from "date-fns";
import { z } from "zod";
import clientPromise from "@/lib/mongodb";
import { TournamentData } from "@/types";
import { TimeControl, Tournament, tcMap } from "@/types";
import { ExtractSafeActionResult } from "@/types";
import { errorLog } from "@/utils/logger";
import { removeDiacritics } from "@/utils/string";
import { action } from "./safeAction";
const inputSchema = z.object({
searchValue: z.string(),
limit: z.number().optional(),
});
export type SearchedTournament = Pick<
Tournament,
| "id"
| "ffeId"
| "date"
| "department"
| "status"
| "timeControl"
| "tournament"
| "town"
| "url"
>;
export const searchTournaments = action(inputSchema, async (input) => {
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB");
const searchTerms = input.searchValue
.split(" ")
.map((s) => removeDiacritics(s.trim()))
.filter((s) => s !== "")
.map((s) => ({ tournament_index: { $regex: s, $options: "i" } }));
const data = await db
.collection("tournaments")
.aggregate<TournamentData>([
{
$addFields: {
dateParts: {
$dateFromString: {
dateString: "$start_date",
format: "%d/%m/%Y",
},
},
},
},
{
$match: {
$and: [
{ federation: { $eq: "FFE" } },
{ dateParts: { $lte: endOfDay(new Date()) } },
...searchTerms,
],
},
},
{
$sort: {
dateParts: -1,
},
},
{ $limit: input.limit ?? 20 },
{
$unset: "dateParts",
},
])
.toArray();
return data.map<SearchedTournament>((t) => {
const timeControl = tcMap[t.time_control] ?? TimeControl.Other;
return {
id: t._id.toString(),
ffeId: t.tournament_id,
tournament: t.tournament,
town: t.town,
department: t.department,
date: t.start_date,
url: t.url,
timeControl,
status: t.status,
};
});
} catch (error) {
errorLog(JSON.stringify(error, null, 2));
throw error;
}
});
-10
View File
@@ -1,10 +0,0 @@
import { initTRPC } from "@trpc/server";
import superjson from "superjson";
const t = initTRPC.create({
transformer: superjson,
});
// Base router and procedure helpers
export const router = t.router;
export const publicProcedure = t.procedure;
+4
View File
@@ -1,5 +1,6 @@
import { LatLngLiteral } from "leaflet";
import { ObjectId } from "mongodb";
import { SafeAction } from "next-safe-action";
import { z } from "zod";
export type Status = "scheduled" | "ongoing" | "finished" | "in-play";
@@ -92,3 +93,6 @@ export type ScrollableElement = Window | HTMLElement;
export type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
export type ExtractSafeActionResult<T> =
T extends SafeAction<infer Schema, infer Result> ? Result : never;
-12
View File
@@ -1,12 +0,0 @@
import { createTRPCReact } from "@trpc/react-query";
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
import type { AppRouter } from "@/server/appRouter";
export type APIRouterInput = inferRouterInputs<AppRouter>;
export type APIRouterOutput = inferRouterOutputs<AppRouter>;
export type TournamentResultsData = APIRouterOutput["fetchTournamentResults"];
export type SearchedTournament = APIRouterOutput["searchTournaments"][number];
export const trpc = createTRPCReact<AppRouter>();