Update packages

This commit is contained in:
Timothy Armes
2024-09-26 16:45:40 +02:00
parent 75fd05a3d7
commit 1c7ad63e03
33 changed files with 1822 additions and 1351 deletions
@@ -23,7 +23,9 @@ export default function Contact() {
setDeleting(true);
const result = await deleteAccount();
if (result.serverError) {
if (result?.validationErrors) {
throw new Error("ERR_VALIDATION");
} else if (result?.serverError) {
throw new Error(result.serverError);
}
@@ -68,7 +70,7 @@ export default function Contact() {
<button
type="button"
onClick={() => router.back()}
className="rounded-lg border border-primary px-5 py-3 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
className="rounded-lg border border-primary px-5 py-3 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
>
{at("cancelButton")}
</button>
+1 -1
View File
@@ -192,7 +192,7 @@ export default function Elo() {
<button
type="button"
onClick={clearForm}
className="rounded-lg border border-primary px-3 py-2 text-center text-sm text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
className="rounded-lg border border-primary px-3 py-2 text-center text-sm text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
>
{t("enterManualResultsButton")}
</button>
@@ -102,7 +102,7 @@ export const ZoneForm = ({
<div className="flex justify-end gap-4">
<button
onClick={onCancel}
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
>
{cancelTitle ?? at("cancelButton")}
</button>
@@ -41,7 +41,9 @@ const EditZone = () => {
zone: data,
});
if (updatedZone.serverError) {
if (updatedZone?.validationErrors) {
throw new Error("ERR_VALIDATION");
} else if (updatedZone?.serverError) {
throw new Error(updatedZone.serverError);
}
+4 -4
View File
@@ -115,14 +115,14 @@ const Zones = () => {
pathname: "/zones/edit/[id]",
params: { id: zone.id },
}}
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
>
{at("editButton")}
</Link>
<button
type="button"
onClick={() => setDeletingZoneId(zone.id)}
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
>
{at("deleteButton")}
</button>
@@ -153,11 +153,11 @@ const Zones = () => {
>
<InfoMessage responseMessage={responseMessage} />
<div className="flex items-center justify-between space-x-4 text-sm font-bold">
<div className="flex items-center justify-between space-x-4 text-sm font-bold">
<button
type="button"
onClick={() => setDeletingZoneId(null)}
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
>
{at("cancelButton")}
</button>
+1 -1
View File
@@ -42,7 +42,7 @@ export const DropdownMenu = ({
</Menu.Button>
)}
<Menu.Items className="z-20 flex w-auto items-start overflow-hidden rounded-md bg-neutral-200 focus:outline-none dark:bg-neutral-600">
<Menu.Items className="z-20 flex w-auto items-start overflow-hidden rounded-md bg-neutral-200 focus:outline-none dark:bg-neutral-600">
<div className="flex flex-col px-1 py-1">
{items.map(({ title, onClick, className, disabled }, i) => (
<Menu.Item key={i}>
+2 -7
View File
@@ -4,12 +4,7 @@ import { useCallback, useEffect, useMemo, useRef } from "react";
import React from "react";
import { useAtomValue, useSetAtom } from "jotai";
import L, {
DomUtil,
LatLngLiteral,
Marker,
MarkerClusterGroupOptions,
} from "leaflet";
import L, { DomUtil, LatLngLiteral, Marker } from "leaflet";
import "leaflet-defaulticon-compatibility";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet.smooth_marker_bouncing";
@@ -70,7 +65,7 @@ type MapProps = {
filters?: React.ReactNode;
legend?: React.ReactNode;
markers: MapMarker[];
iconCreateFunction?: MarkerClusterGroupOptions["iconCreateFunction"];
iconCreateFunction?: L.MarkerClusterGroupOptions["iconCreateFunction"];
};
export const Map = ({
+2 -2
View File
@@ -79,8 +79,8 @@ export const RegionSelect = ({
};
const formatGroupLabel = (data: GroupedOption) => (
<div className="relative -translate-y-1/2 border-b-2 border-primary-500 text-xs font-bold uppercase text-primary-500 ">
<div className="relative top-1/2 inline-block translate-y-1/2 bg-gray-50 pr-2 dark:bg-gray-700 ">
<div className="relative -translate-y-1/2 border-b-2 border-primary-500 text-xs font-bold uppercase text-primary-500">
<div className="relative top-1/2 inline-block translate-y-1/2 bg-gray-50 pr-2 dark:bg-gray-700">
{data.label}
</div>
</div>
+1 -1
View File
@@ -55,7 +55,7 @@ const SearchBar = ({ className }: SearchBarProps) => {
type="search"
id="table-search"
className={twMerge(
"block rounded-lg border border-gray-300 bg-gray-50 p-2.5 px-10 text-sm text-gray-900 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-primary-500",
"block rounded-lg border border-gray-300 bg-gray-50 p-2.5 px-10 text-sm text-gray-900 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-primary-500",
className,
)}
placeholder={t("searchPlaceholder")}
+1 -1
View File
@@ -47,7 +47,7 @@ export const SignInForm = ({ callbackPath }: SignInFormProps) => {
}
});
return () => subscription.unsubscribe();
}, [form, form.watch]);
}, [form, form.watch, responseMessage.message]);
const onSubmit = async ({ email }: SignInFormValues) => {
try {
@@ -39,7 +39,7 @@ export const InputDatePicker = forwardRef<HTMLInputElement, AllProps>(
className={twMerge(
"flex w-full content-center rounded-lg border p-3",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 ",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400",
!error &&
"focus-within:border-primary-500 focus-within:ring-primary-500 dark:focus-within:border-primary-500 dark:focus-within:ring-primary-500",
error && "!border-orange-700 focus:!border-orange-700",
+7 -7
View File
@@ -78,11 +78,7 @@ export const DateField = <
portalId="calendar-portal"
dateFormat={dateFormat}
disabledKeyboardNavigation={true}
formatWeekDay={(day: string) => (
<div className="flex h-8 flex-col items-center justify-center">
{day.slice(0, 3)}
</div>
)}
formatWeekDay={(day: string) => day.slice(0, 3)}
weekDayClassName={() =>
"text-xs h-8 w-8 flex-1 bg-gray-50 text-gray-900 dark:bg-gray-700 dark:text-white"
}
@@ -95,9 +91,13 @@ export const DateField = <
onChange={field.onChange}
onChangeRaw={(e) => {
// Called when the user types in the input
if (e.currentTarget.value) {
if (e?.currentTarget && "value" in e.currentTarget) {
const value = e.currentTarget.value;
const date = parse(value, at("dateParseFormat"), new Date());
const date = parse(
value as string,
at("dateParseFormat"),
new Date(),
);
if (
isValid(date) &&
date.getFullYear() >= min &&
+1 -1
View File
@@ -92,7 +92,7 @@ export const RadioGroupField = <
value={option.value}
className={({ checked }) =>
twMerge(
"flex flex-1 cursor-pointer items-center justify-center rounded-lg border px-5 py-3 text-center font-medium focus:outline-none",
"flex flex-1 cursor-pointer items-center justify-center rounded-lg border px-5 py-3 text-center font-medium focus:outline-none",
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
checked &&
+1 -1
View File
@@ -42,7 +42,7 @@ export const classNames = <Option, IsMulti extends boolean = false>(
menu: () =>
twMerge(
"!z-30 mt-2 rounded-lg border border-gray-200 bg-white p-1",
"border-gray-300 bg-gray-50 text-gray-900",
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
),
groupHeading: () => "mx-3 mt-2 mb-1 text-textGray text-sm uppercase",
+1 -1
View File
@@ -87,7 +87,7 @@ export const TextAreaField = <
disabled={disabled}
className={twMerge(
"flex w-full content-center rounded-lg border p-3",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500",
hasError && "!border-orange-700 focus:!border-orange-700",
disabled && "dark:bg-gray-50",
+1 -1
View File
@@ -60,7 +60,7 @@ export const TextField = <
? isNaN(value)
? ""
: value.toString()
: value ?? "";
: (value ?? "");
};
const output =
@@ -40,7 +40,8 @@ export const TournamentSelectField = <
useState<SearchedTournament | null>(null);
const loadOption = async (ffeId: string) => {
const { data: tournament } = await getTournamentDetails({ ffeId });
const result = await getTournamentDetails({ ffeId });
const tournament = result?.data;
return !tournament
? undefined
@@ -52,10 +53,12 @@ export const TournamentSelectField = <
};
const loadOptions = async (searchValue?: string) => {
const { data: tournaments } = await searchTournaments({
const result = await searchTournaments({
searchValue: searchValue ?? "",
});
const tournaments = result?.data ?? [];
return (tournaments ?? []).map((tournament) => ({
value: tournament.ffeId,
label: tournament.tournament,
@@ -73,7 +76,7 @@ export const TournamentSelectField = <
loadOptions={loadOptions}
isClearable={true}
onInformChange={(data) => {
setSelectedTournament(data ? data[0].data ?? null : null);
setSelectedTournament(data ? (data[0].data ?? null) : null);
onInformChange?.(data);
}}
formatOptionLabel={(option, context) => {
@@ -83,7 +86,7 @@ export const TournamentSelectField = <
<div className="flex items-center gap-2 text-xs uppercase">
<div className="flex-1">{option.data?.town}</div>
<div
className="ml-2 rounded-sm px-1 py-0.5 align-middle text-[9px]/[11px] uppercase text-white"
className="ml-2 rounded-sm px-1 py-0.5 align-middle text-[9px]/[11px] uppercase text-white"
style={{
background: `${TimeControlColours[option.data!.timeControl]}`,
}}
+58 -51
View File
@@ -8,7 +8,7 @@ import { TimeControl } from "@/types";
import { errorLog } from "@/utils/logger";
import { TournamentModel } from "./models/tournamentModel";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
const tcMap: Record<TimeControl, TournamentModel["time_control"]> = {
[TimeControl.Classic]: "Cadence Lente",
@@ -17,61 +17,68 @@ const tcMap: Record<TimeControl, TournamentModel["time_control"]> = {
[TimeControl.Other]: "Other",
};
export const addTournament = action(addTournamentSchema, async (input) => {
try {
await dbConnect();
export const addTournament = actionClient
.schema(addTournamentSchema)
.action(async (input) => {
try {
await dbConnect();
const { name, email, message, tournament } = input;
const { name, email, message, tournament } = input.parsedInput;
const tournamentData: Omit<TournamentModel, "_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 tournamentData: Omit<TournamentModel, "_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 collections.tournaments!.insertOne(tournamentData);
const result = await collections.tournaments!.insertOne(tournamentData);
if (result.insertedId) {
const { tournament, country, date, time_control } = 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 ?? "" },
],
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;
return true;
}
} catch (error) {
errorLog(error);
throw error;
}
} catch (error) {
errorLog(error);
throw error;
}
});
});
+30 -28
View File
@@ -5,32 +5,34 @@ import { z } from "zod";
import { contactUsSchema } from "@/schemas";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
import { actionClient } 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;
}
});
export const contactUs = actionClient
.schema(contactUsSchema)
.action(async (input) => {
try {
const { email, subject, message } = input.parsedInput;
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;
}
});
+27 -25
View File
@@ -8,31 +8,33 @@ import { collections, dbConnect } from "@/server/mongodb";
import { errorLog } from "@/utils/logger";
import { ZoneModel } from "./models/zoneModel";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
export const createZone = action(zoneSchema, async (input) => {
try {
await dbConnect();
export const createZone = actionClient
.schema(zoneSchema)
.action(async (input) => {
try {
await dbConnect();
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
}
const zoneData: ZoneModel = {
...input.parsedInput,
userId: new ObjectId(user.user!.id!),
};
const result = await collections.zones!.insertOne(zoneData);
if (!result.acknowledged) {
throw new Error("ERR_ZONE_INSERT_FAILED");
}
return true;
} catch (error) {
errorLog(error);
throw error;
}
const zoneData: ZoneModel = {
...input,
userId: new ObjectId(user.user!.id!),
};
const result = await collections.zones!.insertOne(zoneData);
if (!result.acknowledged) {
throw new Error("ERR_ZONE_INSERT_FAILED");
}
return true;
} catch (error) {
errorLog(error);
throw error;
}
});
});
+2 -2
View File
@@ -7,9 +7,9 @@ import { adapter, auth } from "@/auth";
import { collections, dbConnect } from "@/server/mongodb";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
export const deleteAccount = action(z.void(), async () => {
export const deleteAccount = actionClient.action(async () => {
try {
await dbConnect();
+27 -23
View File
@@ -7,33 +7,37 @@ import { auth } from "@/auth";
import { collections, dbConnect } from "@/server/mongodb";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
const deleteZoneSchema = z.object({
id: z.string(),
});
export const deleteZone = action(deleteZoneSchema, async ({ id }) => {
try {
await dbConnect();
export const deleteZone = actionClient
.schema(deleteZoneSchema)
.action(async (input) => {
const { id } = input.parsedInput;
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
try {
await dbConnect();
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
}
const result = await collections.zones!.deleteOne({
_id: new ObjectId(id),
userId: new ObjectId(user.user!.id!),
});
if (!result || result.deletedCount !== 1) {
throw new Error("ERR_ZONE_DELETE_FAILED");
}
return true;
} catch (error) {
errorLog(error);
throw error;
}
const result = await collections.zones!.deleteOne({
_id: new ObjectId(id),
userId: new ObjectId(user.user!.id!),
});
if (!result || result.deletedCount !== 1) {
throw new Error("ERR_ZONE_DELETE_FAILED");
}
return true;
} catch (error) {
errorLog(error);
throw error;
}
});
});
+35 -32
View File
@@ -10,43 +10,46 @@ import { collections, dbConnect } from "@/server/mongodb";
import { errorLog } from "@/utils/logger";
import { ZoneModel } from "./models/zoneModel";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
const editZoneSchema = z.object({
id: z.string(),
zone: zoneSchema,
});
export const editZone = action(editZoneSchema, async ({ id, zone }) => {
try {
await dbConnect();
export const editZone = actionClient
.schema(editZoneSchema)
.action(async (input) => {
const { id, zone } = input.parsedInput;
try {
await dbConnect();
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
}
const zoneData: ZoneModel = {
...zone,
userId: new ObjectId(user.user!.id!),
};
const result = await collections.zones!.findOneAndUpdate(
{ _id: new ObjectId(id), userId: new ObjectId(user.user!.id!) },
{ $set: { _id: new ObjectId(id), ...zoneData } },
);
if (!result) {
throw new Error("ERR_ZONE_UPDATE_FAILED");
}
return {
...omit(result, ["_id"]),
id: result._id.toString(),
userId: result.userId.toString(),
};
} catch (error) {
errorLog(error);
throw error;
}
const zoneData: ZoneModel = {
...zone,
userId: new ObjectId(user.user!.id!),
};
const result = await collections.zones!.findOneAndUpdate(
{ _id: new ObjectId(id), userId: new ObjectId(user.user!.id!) },
{ $set: { _id: new ObjectId(id), ...zoneData } },
);
if (!result) {
throw new Error("ERR_ZONE_UPDATE_FAILED");
}
return {
...omit(result, ["_id"]),
id: result._id.toString(),
userId: result.userId.toString(),
};
} catch (error) {
errorLog(error);
throw error;
}
});
});
+8 -8
View File
@@ -5,7 +5,7 @@ import { z } from "zod";
import { fetchTournamentResultsSchema } from "@/schemas";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
const dbSchema = z.array(
z.object({
@@ -106,9 +106,10 @@ const reportFetchError = async (url: string, error: any) => {
}
};
export const fetchTournamentResults = action(
fetchTournamentResultsSchema,
async (input) => {
export const fetchTournamentResults = actionClient
.schema(fetchTournamentResultsSchema)
.action(async (input) => {
const { id } = input.parsedInput;
try {
const headers = new Headers();
const apiKey = process.env.RESULTS_API_KEY;
@@ -118,7 +119,7 @@ export const fetchTournamentResults = action(
}
const rawResults = await fetch(
`${process.env.RESULTS_SCRAPER_URL}${input.id}`,
`${process.env.RESULTS_SCRAPER_URL}${id}`,
{
headers: headers,
},
@@ -155,9 +156,8 @@ export const fetchTournamentResults = action(
})),
);
} catch (error) {
reportFetchError(input.id, error);
reportFetchError(id, error);
errorLog(JSON.stringify(error, null, 2));
throw error;
}
},
);
});
+31 -28
View File
@@ -6,38 +6,41 @@ import { collections, dbConnect } from "@/server/mongodb";
import { TimeControl, tcMap } from "@/types";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
const inputSchema = z.object({
ffeId: z.string(),
});
export const getTournamentDetails = action(inputSchema, async (input) => {
try {
await dbConnect();
const t = await collections.tournaments!.findOne({
tournament_id: input.ffeId,
});
export const getTournamentDetails = actionClient
.schema(inputSchema)
.action(async (input) => {
const { ffeId } = input.parsedInput;
try {
await dbConnect();
const t = await collections.tournaments!.findOne({
tournament_id: ffeId,
});
if (t === null) {
return null;
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;
}
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;
}
});
});
+2 -3
View File
@@ -3,20 +3,19 @@
import { FeatureCollection } from "geojson";
import { omit } from "lodash";
import { ObjectId } from "mongodb";
import { z } from "zod";
import { auth } from "@/auth";
import { collections, dbConnect } from "@/server/mongodb";
import { ZoneModel } from "./models/zoneModel";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
export type Zone = Omit<ZoneModel, "userId" | "features"> & {
id: string;
features: FeatureCollection;
};
export const myZones = action(z.void(), async () => {
export const myZones = actionClient.action(async () => {
await dbConnect();
const user = await auth();
+58 -55
View File
@@ -8,7 +8,7 @@ import { TimeControl, Tournament, tcMap } from "@/types";
import { errorLog } from "@/utils/logger";
import { removeDiacritics } from "@/utils/string";
import { action } from "./safeAction";
import { actionClient } from "./safeAction";
const inputSchema = z.object({
searchValue: z.string(),
@@ -28,66 +28,69 @@ export type SearchedTournament = Pick<
| "url"
>;
export const searchTournaments = action(inputSchema, async (input) => {
try {
await dbConnect();
export const searchTournaments = actionClient
.schema(inputSchema)
.action(async (input) => {
const { searchValue, limit } = input.parsedInput;
try {
await dbConnect();
const searchTerms = input.searchValue
.split(" ")
.map((s) => removeDiacritics(s.trim()))
.filter((s) => s !== "")
.map((s) => ({ tournament_index: { $regex: s, $options: "i" } }));
const searchTerms = searchValue
.split(" ")
.map((s) => removeDiacritics(s.trim()))
.filter((s) => s !== "")
.map((s) => ({ tournament_index: { $regex: s, $options: "i" } }));
const data = await collections
.tournaments!.aggregate([
{
$addFields: {
dateParts: {
$dateFromString: {
dateString: "$start_date",
format: "%d/%m/%Y",
const data = await collections
.tournaments!.aggregate([
{
$addFields: {
dateParts: {
$dateFromString: {
dateString: "$start_date",
format: "%d/%m/%Y",
},
},
},
},
},
{
$match: {
$and: [
{ federation: { $eq: "FFE" } },
{ dateParts: { $lte: endOfDay(new Date()) } },
...searchTerms,
],
{
$match: {
$and: [
{ federation: { $eq: "FFE" } },
{ dateParts: { $lte: endOfDay(new Date()) } },
...searchTerms,
],
},
},
},
{
$sort: {
dateParts: -1,
{
$sort: {
dateParts: -1,
},
},
},
{ $limit: input.limit ?? 20 },
{
$unset: "dateParts",
},
])
.toArray();
{ $limit: limit ?? 20 },
{
$unset: "dateParts",
},
])
.toArray();
return data.map<SearchedTournament>((t) => {
const timeControl = tcMap[t.time_control] ?? TimeControl.Other;
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;
}
});
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 -4
View File
@@ -1,5 +1,4 @@
import { LatLngLiteral } from "leaflet";
import { SafeAction } from "next-safe-action";
import { TournamentModel } from "./server/models/tournamentModel";
@@ -65,7 +64,5 @@ export type Path<T, K extends keyof T = keyof T> = K extends string
? T[K] extends Record<string, unknown>
? `${K}.${Path<T[K], keyof T[K]>}`
: K
: never;
export type ExtractSafeActionResult<T> =
T extends SafeAction<infer Schema, infer Result> ? Result : never;
: never;
+1 -1
View File
@@ -110,7 +110,7 @@ export interface NodemailerConfig extends EmailConfig {
theme: any;
request: Request;
}) => Awaitable<void>;
options: NodemailerUserConfig;
options?: NodemailerUserConfig;
}
export type NodemailerUserConfig = Omit<