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
+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;