mirror of
https://github.com/TheRealOwenRees/echecsfrance.git
synced 2026-07-23 04:26:57 +00:00
Move from TRPC to server actions
This commit is contained in:
Vendored
+1
-2
@@ -29,12 +29,11 @@
|
|||||||
"spiderified",
|
"spiderified",
|
||||||
"superjson",
|
"superjson",
|
||||||
"tailwindcss",
|
"tailwindcss",
|
||||||
"tanstack",
|
"tanstack",Ò
|
||||||
"timothyarmes",
|
"timothyarmes",
|
||||||
"tournoi",
|
"tournoi",
|
||||||
"tournois",
|
"tournois",
|
||||||
"trivago",
|
"trivago",
|
||||||
"TRPC",
|
|
||||||
"unspiderfied",
|
"unspiderfied",
|
||||||
"unspiderfy"
|
"unspiderfy"
|
||||||
],
|
],
|
||||||
|
|||||||
+3
-5
@@ -17,11 +17,8 @@
|
|||||||
"@hookform/resolvers": "^3.3.3",
|
"@hookform/resolvers": "^3.3.3",
|
||||||
"@kodingdotninja/use-tailwind-breakpoint": "^0.0.5",
|
"@kodingdotninja/use-tailwind-breakpoint": "^0.0.5",
|
||||||
"@next/bundle-analyzer": "^14.0.4",
|
"@next/bundle-analyzer": "^14.0.4",
|
||||||
"@tanstack/react-query": "^4.35.0",
|
"@tanstack/react-query": "^5.29.0",
|
||||||
"@trivago/prettier-plugin-sort-imports": "^4.2.0",
|
"@trivago/prettier-plugin-sort-imports": "^4.2.0",
|
||||||
"@trpc/client": "^10.45.0",
|
|
||||||
"@trpc/react-query": "^10.45.0",
|
|
||||||
"@trpc/server": "^10.45.0",
|
|
||||||
"@types/node": "^20.8.4",
|
"@types/node": "^20.8.4",
|
||||||
"autoprefixer": "^10.4.16",
|
"autoprefixer": "^10.4.16",
|
||||||
"date-fns": "^2.30.0",
|
"date-fns": "^2.30.0",
|
||||||
@@ -35,6 +32,7 @@
|
|||||||
"next": "^14.0.4",
|
"next": "^14.0.4",
|
||||||
"next-intl": "^3.3.2",
|
"next-intl": "^3.3.2",
|
||||||
"next-pwa": "^5.6.0",
|
"next-pwa": "^5.6.0",
|
||||||
|
"next-safe-action": "^6.2.0",
|
||||||
"postcss": "8.4.33",
|
"postcss": "8.4.33",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-date-range": "^1.4.0",
|
"react-date-range": "^1.4.0",
|
||||||
@@ -65,8 +63,8 @@
|
|||||||
"@types/nodemailer": "^6.4.8",
|
"@types/nodemailer": "^6.4.8",
|
||||||
"@types/react": "^18.2.27",
|
"@types/react": "^18.2.27",
|
||||||
"@types/react-date-range": "^1.4.9",
|
"@types/react-date-range": "^1.4.9",
|
||||||
"@types/react-dom": "^18.2.18",
|
|
||||||
"@types/react-datepicker": "^4.15.0",
|
"@types/react-datepicker": "^4.15.0",
|
||||||
|
"@types/react-dom": "^18.2.18",
|
||||||
"@types/react-input-mask": "^3.0.2",
|
"@types/react-input-mask": "^3.0.2",
|
||||||
"eslint": "^8.54.0",
|
"eslint": "^8.54.0",
|
||||||
"eslint-config-next": "^14.0.4",
|
"eslint-config-next": "^14.0.4",
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ import { SwitchField } from "@/components/form/SwitchField";
|
|||||||
import { TextAreaField } from "@/components/form/TextAreaField";
|
import { TextAreaField } from "@/components/form/TextAreaField";
|
||||||
import { TextField } from "@/components/form/TextField";
|
import { TextField } from "@/components/form/TextField";
|
||||||
import { addTournamentSchema } from "@/schemas";
|
import { addTournamentSchema } from "@/schemas";
|
||||||
|
import { addTournament } from "@/server/addTournament";
|
||||||
import { TimeControl } from "@/types";
|
import { TimeControl } from "@/types";
|
||||||
import { trpc } from "@/utils/trpc";
|
|
||||||
|
|
||||||
type TournamentFormValues = z.infer<typeof addTournamentSchema>;
|
type TournamentFormValues = z.infer<typeof addTournamentSchema>;
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ const Map = dynamic(() => import("./Map"), {
|
|||||||
const TournamentForm = () => {
|
const TournamentForm = () => {
|
||||||
const t = useTranslations("AddTournament");
|
const t = useTranslations("AddTournament");
|
||||||
const at = useTranslations("App");
|
const at = useTranslations("App");
|
||||||
const addTournament = trpc.addTournament.useMutation();
|
|
||||||
const [responseMessage, setResponseMessage] = useState({
|
const [responseMessage, setResponseMessage] = useState({
|
||||||
isSuccessful: false,
|
isSuccessful: false,
|
||||||
message: "",
|
message: "",
|
||||||
@@ -48,7 +48,7 @@ const TournamentForm = () => {
|
|||||||
|
|
||||||
const onSubmit = async (data: TournamentFormValues) => {
|
const onSubmit = async (data: TournamentFormValues) => {
|
||||||
try {
|
try {
|
||||||
await addTournament.mutateAsync(data);
|
await addTournament(data);
|
||||||
setResponseMessage({
|
setResponseMessage({
|
||||||
isSuccessful: true,
|
isSuccessful: true,
|
||||||
message: t("success"),
|
message: t("success"),
|
||||||
|
|||||||
@@ -12,14 +12,13 @@ import { clearMessage } from "@/components/InfoMessage";
|
|||||||
import { TextAreaField } from "@/components/form/TextAreaField";
|
import { TextAreaField } from "@/components/form/TextAreaField";
|
||||||
import { TextField } from "@/components/form/TextField";
|
import { TextField } from "@/components/form/TextField";
|
||||||
import { contactUsSchema } from "@/schemas";
|
import { contactUsSchema } from "@/schemas";
|
||||||
import { trpc } from "@/utils/trpc";
|
import { contactUs } from "@/server/contactUs";
|
||||||
|
|
||||||
type TournamentFormValues = z.infer<typeof contactUsSchema>;
|
type TournamentFormValues = z.infer<typeof contactUsSchema>;
|
||||||
|
|
||||||
const ContactForm = () => {
|
const ContactForm = () => {
|
||||||
const t = useTranslations("Contact");
|
const t = useTranslations("Contact");
|
||||||
|
|
||||||
const contactUs = trpc.contactUs.useMutation();
|
|
||||||
const [responseMessage, setResponseMessage] = useState({
|
const [responseMessage, setResponseMessage] = useState({
|
||||||
isSuccessful: false,
|
isSuccessful: false,
|
||||||
message: "",
|
message: "",
|
||||||
@@ -31,7 +30,7 @@ const ContactForm = () => {
|
|||||||
|
|
||||||
const onSubmit = async (data: TournamentFormValues) => {
|
const onSubmit = async (data: TournamentFormValues) => {
|
||||||
try {
|
try {
|
||||||
await contactUs.mutateAsync(data);
|
await contactUs(data);
|
||||||
setResponseMessage({
|
setResponseMessage({
|
||||||
isSuccessful: true,
|
isSuccessful: true,
|
||||||
message: t("success"),
|
message: t("success"),
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import { last } from "lodash";
|
|||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { twMerge } from "tailwind-merge";
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
|
import { TournamentResultsData } from "@/server/fetchTournamentResults";
|
||||||
import { getNewRating } from "@/utils/eloCalculator";
|
import { getNewRating } from "@/utils/eloCalculator";
|
||||||
import { TournamentResultsData } from "@/utils/trpc";
|
|
||||||
|
|
||||||
type TournamentResultsProps = {
|
type TournamentResultsProps = {
|
||||||
results: TournamentResultsData;
|
results: TournamentResultsData;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useCallback, useEffect, useMemo } from "react";
|
import { useCallback, useEffect, useMemo } from "react";
|
||||||
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { isEmpty, sortBy } from "lodash";
|
import { isEmpty, sortBy } from "lodash";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||||
@@ -13,8 +14,8 @@ import { Spinner } from "@/components/Spinner";
|
|||||||
import { SelectField } from "@/components/form/SelectField";
|
import { SelectField } from "@/components/form/SelectField";
|
||||||
import { TournamentSelectField } from "@/components/form/TournamentSelectField";
|
import { TournamentSelectField } from "@/components/form/TournamentSelectField";
|
||||||
import { fetchTournamentResultsSchema } from "@/schemas";
|
import { fetchTournamentResultsSchema } from "@/schemas";
|
||||||
|
import { fetchTournamentResults } from "@/server/fetchTournamentResults";
|
||||||
import { Link } from "@/utils/navigation";
|
import { Link } from "@/utils/navigation";
|
||||||
import { trpc } from "@/utils/trpc";
|
|
||||||
|
|
||||||
import { KFactor } from "./KFactor";
|
import { KFactor } from "./KFactor";
|
||||||
import { ManualEloForm } from "./ManualEloForm";
|
import { ManualEloForm } from "./ManualEloForm";
|
||||||
@@ -55,21 +56,18 @@ export default function Elo() {
|
|||||||
data: allResults,
|
data: allResults,
|
||||||
isFetching,
|
isFetching,
|
||||||
error,
|
error,
|
||||||
} = trpc.fetchTournamentResults.useQuery(
|
} = useQuery({
|
||||||
{
|
queryKey: ["fetchTournamentResults", { id: tournamentId?.trim() }],
|
||||||
id: tournamentId?.trim(),
|
queryFn: async () => fetchTournamentResults({ id: tournamentId?.trim() }),
|
||||||
},
|
refetchOnWindowFocus: false,
|
||||||
{
|
staleTime: Infinity,
|
||||||
refetchOnWindowFocus: false,
|
gcTime: 10 * 60 * 1000,
|
||||||
staleTime: Infinity,
|
enabled: hasTournamentId,
|
||||||
cacheTime: 10 * 60 * 1000,
|
retry: false,
|
||||||
enabled: hasTournamentId,
|
});
|
||||||
retry: false,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const playerOptions = sortBy(
|
const playerOptions = sortBy(
|
||||||
(allResults ?? []).map((player) => ({
|
(allResults?.data ?? []).map((player) => ({
|
||||||
value: player.id,
|
value: player.id,
|
||||||
label: player.name,
|
label: player.name,
|
||||||
})),
|
})),
|
||||||
@@ -173,7 +171,7 @@ export default function Elo() {
|
|||||||
console.error(error);
|
console.error(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
const playerResults = allResults?.find((p) => p.id === player);
|
const playerResults = allResults?.data?.find((p) => p.id === player);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="grid place-items-center bg-white pb-20 dark:bg-gray-800">
|
<section className="grid place-items-center bg-white pb-20 dark:bg-gray-800">
|
||||||
@@ -215,7 +213,7 @@ export default function Elo() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{error && (
|
{error instanceof Error && (
|
||||||
<div className="mt-8 text-center text-error">
|
<div className="mt-8 text-center text-error">
|
||||||
{error.message.startsWith("ERR_")
|
{error.message.startsWith("ERR_")
|
||||||
? t(error.message as TranslationKey)
|
? t(error.message as TranslationKey)
|
||||||
@@ -269,7 +267,7 @@ export default function Elo() {
|
|||||||
<TournamentResults
|
<TournamentResults
|
||||||
playerId={player}
|
playerId={player}
|
||||||
kFactor={parseInt(kFactor)}
|
kFactor={parseInt(kFactor)}
|
||||||
results={allResults ?? []}
|
results={allResults?.data ?? []}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -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 { FieldPath, FieldValues } from "react-hook-form";
|
||||||
|
|
||||||
import { TimeControlColours } from "@/constants";
|
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";
|
import { AsyncSelectField, AsyncSelectFieldProps } from "./AsyncSelectField";
|
||||||
|
|
||||||
@@ -27,10 +31,9 @@ export const TournamentSelectField = <
|
|||||||
...rest
|
...rest
|
||||||
}: TournamentSelectFieldProps<TFieldValues, TFieldName>) => {
|
}: TournamentSelectFieldProps<TFieldValues, TFieldName>) => {
|
||||||
const at = useTranslations("App");
|
const at = useTranslations("App");
|
||||||
const client = trpc.useContext();
|
|
||||||
|
|
||||||
const loadOption = async (ffeId: string) => {
|
const loadOption = async (ffeId: string) => {
|
||||||
const tournament = await client.getTournamentDetails.fetch({ ffeId });
|
const { data: tournament } = await getTournamentDetails({ ffeId });
|
||||||
|
|
||||||
return !tournament
|
return !tournament
|
||||||
? undefined
|
? undefined
|
||||||
@@ -42,7 +45,7 @@ export const TournamentSelectField = <
|
|||||||
};
|
};
|
||||||
|
|
||||||
const loadOptions = async (searchValue?: string) => {
|
const loadOptions = async (searchValue?: string) => {
|
||||||
const tournaments = await client.searchTournaments.fetch({
|
const { data: tournaments } = await searchTournaments({
|
||||||
searchValue: searchValue ?? "",
|
searchValue: searchValue ?? "",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { Provider } from "jotai";
|
import { Provider } from "jotai";
|
||||||
|
|
||||||
import { useDynamicViewportUnits } from "@/hooks/useDynamicViewportUnits";
|
import { useDynamicViewportUnits } from "@/hooks/useDynamicViewportUnits";
|
||||||
|
|
||||||
import { TrpcProvider } from "./TrpcProvider";
|
|
||||||
|
|
||||||
export default function Providers({ children }: { children: React.ReactNode }) {
|
export default function Providers({ children }: { children: React.ReactNode }) {
|
||||||
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
useDynamicViewportUnits();
|
useDynamicViewportUnits();
|
||||||
return (
|
return (
|
||||||
<Provider>
|
<Provider>
|
||||||
<TrpcProvider>{children}</TrpcProvider>
|
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||||
</Provider>
|
</Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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;
|
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
+15
-13
@@ -1,9 +1,11 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { fetchTournamentResultsSchema } from "@/schemas";
|
import { fetchTournamentResultsSchema } from "@/schemas";
|
||||||
import { errorLog } from "@/utils/logger";
|
import { errorLog } from "@/utils/logger";
|
||||||
|
|
||||||
import { publicProcedure } from "../trpc";
|
import { action } from "./safeAction";
|
||||||
|
|
||||||
const dbSchema = z.array(
|
const dbSchema = z.array(
|
||||||
z.object({
|
z.object({
|
||||||
@@ -43,6 +45,8 @@ const outputSchema = z.array(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export type TournamentResultsData = z.infer<typeof outputSchema>;
|
||||||
|
|
||||||
const getEloDetails = (elo: string | null) => {
|
const getEloDetails = (elo: string | null) => {
|
||||||
if (elo === null || elo === "") {
|
if (elo === null || elo === "") {
|
||||||
return { elo: 0, estimated: false, national: false };
|
return { elo: 0, estimated: false, national: false };
|
||||||
@@ -102,10 +106,9 @@ const reportFetchError = async (url: string, error: any) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchTournamentResults = publicProcedure
|
export const fetchTournamentResults = action(
|
||||||
.input(fetchTournamentResultsSchema)
|
fetchTournamentResultsSchema,
|
||||||
.output(outputSchema)
|
async (input) => {
|
||||||
.query(async ({ input }) => {
|
|
||||||
try {
|
try {
|
||||||
const headers = new Headers();
|
const headers = new Headers();
|
||||||
const apiKey = process.env.RESULTS_API_KEY;
|
const apiKey = process.env.RESULTS_API_KEY;
|
||||||
@@ -114,8 +117,6 @@ export const fetchTournamentResults = publicProcedure
|
|||||||
headers.append("api-key", apiKey);
|
headers.append("api-key", apiKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(input.id);
|
|
||||||
|
|
||||||
const rawResults = await fetch(
|
const rawResults = await fetch(
|
||||||
`${process.env.RESULTS_SCRAPER_URL}${input.id}`,
|
`${process.env.RESULTS_SCRAPER_URL}${input.id}`,
|
||||||
{
|
{
|
||||||
@@ -130,8 +131,8 @@ export const fetchTournamentResults = publicProcedure
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parsedResults = dbSchema.parse(results);
|
const parsedResults = dbSchema.parse(results);
|
||||||
return parsedResults.map<z.infer<typeof outputSchema>[number]>(
|
return outputSchema.parse(
|
||||||
(player) => ({
|
parsedResults.map<z.infer<typeof outputSchema>[number]>((player) => ({
|
||||||
id: player.id,
|
id: player.id,
|
||||||
name: player.name,
|
name: player.name,
|
||||||
...getEloDetails(player.elo),
|
...getEloDetails(player.elo),
|
||||||
@@ -140,17 +141,18 @@ export const fetchTournamentResults = publicProcedure
|
|||||||
result.colour === "B"
|
result.colour === "B"
|
||||||
? "white"
|
? "white"
|
||||||
: result.colour === "N"
|
: result.colour === "N"
|
||||||
? "black"
|
? "black"
|
||||||
: "",
|
: "",
|
||||||
opponent: result.opponent_name,
|
opponent: result.opponent_name,
|
||||||
...getResultDetails(result),
|
...getResultDetails(result),
|
||||||
...getEloDetails(result.opponent_elo),
|
...getEloDetails(result.opponent_elo),
|
||||||
})),
|
})),
|
||||||
}),
|
})),
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
reportFetchError(input.id, error);
|
reportFetchError(input.id, error);
|
||||||
errorLog(JSON.stringify(error, null, 2));
|
errorLog(JSON.stringify(error, null, 2));
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
});
|
},
|
||||||
|
);
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { createSafeActionClient } from "next-safe-action";
|
||||||
|
|
||||||
|
export const action = createSafeActionClient();
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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;
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { LatLngLiteral } from "leaflet";
|
import { LatLngLiteral } from "leaflet";
|
||||||
import { ObjectId } from "mongodb";
|
import { ObjectId } from "mongodb";
|
||||||
|
import { SafeAction } from "next-safe-action";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
export type Status = "scheduled" | "ongoing" | "finished" | "in-play";
|
export type Status = "scheduled" | "ongoing" | "finished" | "in-play";
|
||||||
@@ -92,3 +93,6 @@ export type ScrollableElement = Window | HTMLElement;
|
|||||||
export type Prettify<T> = {
|
export type Prettify<T> = {
|
||||||
[K in keyof T]: T[K];
|
[K in keyof T]: T[K];
|
||||||
} & {};
|
} & {};
|
||||||
|
|
||||||
|
export type ExtractSafeActionResult<T> =
|
||||||
|
T extends SafeAction<infer Schema, infer Result> ? Result : never;
|
||||||
|
|||||||
@@ -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>();
|
|
||||||
Reference in New Issue
Block a user