Zone collection + creation

Zone create UI flow
This commit is contained in:
Timothy Armes
2024-04-11 09:05:05 +02:00
parent 1da389a24a
commit 9f12a00030
21 changed files with 431 additions and 90 deletions
+1
View File
@@ -9,6 +9,7 @@ const withNextIntl = require("next-intl/plugin")("./src/i18n.ts");
const withPWA = require("next-pwa")({ const withPWA = require("next-pwa")({
dest: "public", dest: "public",
disable: process.env.NODE_ENV === "development",
}); });
module.exports = nextConfig; module.exports = nextConfig;
@@ -11,7 +11,7 @@ import { useFormContext, useWatch } from "react-hook-form";
import { MapContainer, Marker, TileLayer } from "react-leaflet"; import { MapContainer, Marker, TileLayer } from "react-leaflet";
import { mapBoundsAtom } from "@/atoms"; import { mapBoundsAtom } from "@/atoms";
import MapEvents from "@/components/MapEvents"; import { MapEvents } from "@/components/MapEvents";
const center: LatLngLiteral = { lat: 47.0844, lng: 2.3964 }; const center: LatLngLiteral = { lat: 47.0844, lng: 2.3964 };
@@ -59,7 +59,7 @@ const TournamentForm = () => {
} catch (err: unknown) { } catch (err: unknown) {
console.log(err); console.log(err);
setResponseMessage({ setResponseMessage({
isSuccessful: true, isSuccessful: false,
message: t("failure"), message: t("failure"),
}); });
@@ -53,7 +53,7 @@ export default function SignIn() {
console.log(err); console.log(err);
setResponseMessage({ setResponseMessage({
isSuccessful: true, isSuccessful: false,
message: t("failure"), message: t("failure"),
}); });
@@ -41,7 +41,7 @@ const ContactForm = () => {
} catch (err: unknown) { } catch (err: unknown) {
console.log(err); console.log(err);
setResponseMessage({ setResponseMessage({
isSuccessful: true, isSuccessful: false,
message: t("failure"), message: t("failure"),
}); });
@@ -12,9 +12,21 @@ import { ZoneEditorField } from "@/components/form/ZoneEditorField";
import { zoneSchema } from "@/schemas"; import { zoneSchema } from "@/schemas";
import { TimeControl } from "@/types"; import { TimeControl } from "@/types";
type ZoneFormValues = z.infer<typeof zoneSchema>; export type ZoneFormValues = z.infer<typeof zoneSchema>;
export const ZoneForm = () => { type ZoneFormProps = {
onSubmit: (data: ZoneFormValues) => Promise<void>;
onCancel: () => void;
submitTitle?: string;
cancelTitle?: string;
};
export const ZoneForm = ({
onSubmit,
onCancel,
submitTitle,
cancelTitle,
}: ZoneFormProps) => {
const t = useTranslations("Zones"); const t = useTranslations("Zones");
const at = useTranslations("App"); const at = useTranslations("App");
const form = useForm<ZoneFormValues>({ const form = useForm<ZoneFormValues>({
@@ -30,16 +42,7 @@ export const ZoneForm = () => {
}, },
}); });
const onSubmit = async (data: ZoneFormValues) => {
try {
console.log(data);
} catch (err: unknown) {
console.log(err);
}
};
return ( return (
<div className="mx-auto max-w-screen-md px-4 py-8 lg:py-16">
<FormProvider {...form}> <FormProvider {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8"> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<div className="grid grid-cols-3 items-start gap-6"> <div className="grid grid-cols-3 items-start gap-6">
@@ -82,15 +85,24 @@ export const ZoneForm = () => {
<ZoneEditorField name="features" control={form.control} /> <ZoneEditorField name="features" control={form.control} />
</section> </section>
</div> </div>
<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"
>
{cancelTitle ?? at("cancelButton")}
</button>
<button <button
disabled={form.formState.isSubmitting} disabled={form.formState.isSubmitting}
type="submit" type="submit"
className="rounded-lg bg-primary-600 px-5 py-3 text-center text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:hover:bg-primary-700 dark:focus:ring-primary-800 sm:w-fit" className="rounded-lg bg-primary-600 px-5 py-3 text-center text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:hover:bg-primary-700 dark:focus:ring-primary-800 sm:w-fit"
> >
{t("saveButton")} {submitTitle ?? at("saveButton")}
</button> </button>
</div>
</form> </form>
</FormProvider> </FormProvider>
</div>
); );
}; };
@@ -0,0 +1,41 @@
import * as React from "react";
import L, { LatLngLiteral } from "leaflet";
import "leaflet-defaulticon-compatibility";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet/dist/leaflet.css";
import { FeatureGroup, GeoJSON, MapContainer, TileLayer } from "react-leaflet";
import { MapEvents } from "@/components/MapEvents";
import type { ZoneModel } from "@/server/models/zoneModel";
const center: LatLngLiteral = { lat: 47.0844, lng: 2.3964 };
export type ZoneThumbnailProps = {
features: ZoneModel["features"];
size: number;
};
export const ZoneThumbnail = ({ features, size }: ZoneThumbnailProps) => {
return (
<MapContainer
center={center}
zoom={5}
zoomControl={false}
scrollWheelZoom={false}
dragging={false}
style={{ height: size, width: size }}
attributionControl={false}
>
<MapEvents bounds={L.geoJson(features).getBounds()} />
<TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<GeoJSON data={features} />
</MapContainer>
);
};
export default ZoneThumbnail;
+30 -8
View File
@@ -1,28 +1,50 @@
"use client"; "use client";
import { FeatureCollection } from "geojson"; import { useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { ZoneForm } from "../components/ZoneForm"; import InfoMessage, { clearMessage } from "@/components/InfoMessage";
import { createZone } from "@/server/createZone";
import { useRouter } from "@/utils/navigation";
type ZoneFormValues = { import { ZoneForm, ZoneFormValues } from "../components/ZoneForm";
features: FeatureCollection;
};
const CreateZone = () => { const CreateZone = () => {
const t = useTranslations("Zones"); const t = useTranslations("Zones");
const router = useRouter();
const [responseMessage, setResponseMessage] = useState({
isSuccessful: false,
message: "",
});
const onSubmit = async (data: ZoneFormValues) => { const onSubmit = async (data: ZoneFormValues) => {
try { try {
console.log(data); await createZone(data);
router.push("/zones");
} catch (err: unknown) { } catch (err: unknown) {
console.log(err); console.log(err);
setResponseMessage({
isSuccessful: false,
message: t("createFailure"),
});
clearMessage(setResponseMessage);
} }
}; };
return ( return (
<div className="mx-auto max-w-screen-md px-4 py-8 lg:py-16"> <div className="mx-auto max-w-screen-md px-4 pb-20 pt-8 lg:pt-16">
<ZoneForm /> <h2
className="mb-4 text-center text-4xl font-extrabold tracking-tight text-gray-900 dark:text-white"
data-test="header2"
>
{t("createTitle")}
</h2>
<ZoneForm onSubmit={onSubmit} onCancel={() => router.push("/zones")} />
<InfoMessage responseMessage={responseMessage} />
</div> </div>
); );
}; };
+120
View File
@@ -0,0 +1,120 @@
"use client";
import React from "react";
import { useQuery } from "@tanstack/react-query";
import { useFormatter, useTranslations } from "next-intl";
import dynamic from "next/dynamic";
import { IoAdd } from "react-icons/io5";
import { Spinner } from "@/components/Spinner";
import { myZones } from "@/server/myZones";
import { TimeControl } from "@/types";
import { Link } from "@/utils/navigation";
const ZoneThumbnail = dynamic(() => import("./components/ZoneThumbnail"), {
ssr: false,
loading: () => <div className="h-[200px] w-[200px] bg-gray-200" />,
});
const Zones = () => {
const t = useTranslations("Zones");
const at = useTranslations("App");
const format = useFormatter();
const { data, isFetching, error } = useQuery({
queryKey: ["zones"],
queryFn: async () => myZones(),
refetchOnWindowFocus: false,
staleTime: Infinity,
gcTime: 10 * 60 * 1000,
retry: false,
});
const zones = data?.data ?? [];
return (
<div className="mx-auto max-w-screen-md px-4 py-8 lg:py-16">
<h2
className="mb-4 text-center text-4xl font-extrabold tracking-tight text-gray-900 dark:text-white"
data-test="header2"
>
{t("title")}
</h2>
<p className="mb-8 text-center font-light text-gray-500 dark:text-gray-400 sm:text-xl lg:mb-16">
{t("info")}
</p>
{isFetching ? (
<div className="mt-8 flex justify-center">
<Spinner />
</div>
) : (
<div className="flex flex-col gap-8">
{zones?.map((zone) => {
const notifications = [
...(zone.classicNotifications ? [TimeControl.Classic] : []),
...(zone.rapidNotifications ? [TimeControl.Rapid] : []),
...(zone.blitzNotifications ? [TimeControl.Blitz] : []),
];
console.log(notifications);
const notificationsList = format.list(
notifications.map((tc) => at("timeControlEnumInline", { tc })),
{ type: "conjunction" },
);
return (
<div
className="flex gap-4 text-gray-900 dark:text-white"
key={zone.id}
>
<ZoneThumbnail features={zone.features} size={200} />
<div className="flex flex-1 flex-col justify-between">
<h3 className="text-xl font-semibold text-gray-900 dark:text-white">
{zone.name}
</h3>
<div>
{notifications.length === 0
? t("noNotifications")
: t.rich("withNotifications", {
list: notificationsList,
b: (str) => <b>{str}</b>,
})}
</div>
<div className="flex gap-4">
<button
type="button"
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"
>
{t("editButton")}
</button>
<button
type="button"
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"
>
{t("deleteButton")}
</button>
</div>
</div>
</div>
);
})}
</div>
)}
<div className="mt-12 flex justify-center gap-4">
<Link
href={`/zones/create`}
className="rounded-lg bg-primary-600 px-5 py-3 text-center text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:hover:bg-primary-700 dark:focus:ring-primary-800 sm:w-fit"
>
<IoAdd className="mr-2 inline-block h-5 w-5" />
{t("addZoneButton")}
</Link>
</div>
</div>
);
};
export default Zones;
+2 -2
View File
@@ -19,7 +19,7 @@ import { LayerGroup, MapContainer, TileLayer } from "react-leaflet";
import MarkerClusterGroup from "react-leaflet-cluster"; import MarkerClusterGroup from "react-leaflet-cluster";
import { debouncedHoveredListIdAtom, mapBoundsAtom } from "@/atoms"; import { debouncedHoveredListIdAtom, mapBoundsAtom } from "@/atoms";
import MapEvents from "@/components/MapEvents"; import { MapEvents } from "@/components/MapEvents";
export type MarkerRef = { export type MarkerRef = {
getMarker: () => L.Marker<any>; getMarker: () => L.Marker<any>;
@@ -235,7 +235,7 @@ export const Map = ({
} }
}} }}
> >
<MapEvents /> <MapEvents updateMapBoundsAtom />
<TileLayer <TileLayer
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
+19 -9
View File
@@ -13,18 +13,29 @@ import { mapBoundsAtom } from "@/atoms";
// Add Leaflet.GestureHandling for improved desktop and mobile touch gestures // Add Leaflet.GestureHandling for improved desktop and mobile touch gestures
L.Map.addInitHook("addHandler", "gestureHandling", GestureHandling); L.Map.addInitHook("addHandler", "gestureHandling", GestureHandling);
const MapEvents = () => { const worldBounds = L.latLngBounds(L.latLng(-90, -180), L.latLng(90, 180));
const franceBounds = L.latLngBounds(
L.latLng(42.08, -5.12),
L.latLng(51.17, 9.53),
);
type MapEventsProps = {
bounds?: L.LatLngBounds;
updateMapBoundsAtom?: boolean;
};
export const MapEvents = ({
bounds = franceBounds,
updateMapBoundsAtom = false,
}: MapEventsProps) => {
const locale = useLocale(); const locale = useLocale();
const t = useTranslations("Map"); const t = useTranslations("Map");
const map = useMap(); const map = useMap();
const setMapBounds = useSetAtom(mapBoundsAtom); const setMapBounds = useSetAtom(mapBoundsAtom);
const [isPending, startTransition] = useTransition(); const [isPending, startTransition] = useTransition();
const worldBounds = L.latLngBounds(L.latLng(-90, -180), L.latLng(90, 180)); const map = useMapEvent("moveend", () => {
const franceBounds = L.latLngBounds( if (!updateMapBoundsAtom) return;
L.latLng(42.08, -5.12),
L.latLng(51.17, 9.53),
);
useMapEvent("moveend", () => { useMapEvent("moveend", () => {
// Set the map bounds atoms when the user pans/zooms // Set the map bounds atoms when the user pans/zooms
@@ -35,7 +46,8 @@ const MapEvents = () => {
// Viewport agnostic centering of France & max world bounds // Viewport agnostic centering of France & max world bounds
useEffect(() => { useEffect(() => {
map.setView(franceBounds.getCenter(), map.getBoundsZoom(franceBounds)); const zoom = map.getBoundsZoom(bounds);
map.setView(bounds.getCenter(), zoom === Infinity ? 10 : zoom);
map.setMaxBounds(worldBounds); map.setMaxBounds(worldBounds);
map.options.maxBoundsViscosity = 1.0; // Prevents going past bounds while dragging map.options.maxBoundsViscosity = 1.0; // Prevents going past bounds while dragging
@@ -65,5 +77,3 @@ const MapEvents = () => {
return null; return null;
}; };
export default MapEvents;
+3 -8
View File
@@ -6,15 +6,10 @@ import "leaflet-defaulticon-compatibility";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css"; import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css";
import "leaflet-draw/dist/leaflet.draw.css"; import "leaflet-draw/dist/leaflet.draw.css";
import "leaflet/dist/leaflet.css"; import "leaflet/dist/leaflet.css";
import { import { FeatureGroup, MapContainer, TileLayer } from "react-leaflet";
FeatureGroup,
MapContainer,
TileLayer,
ZoomControl,
} from "react-leaflet";
import { EditControl } from "react-leaflet-draw"; import { EditControl } from "react-leaflet-draw";
import MapEvents from "../MapEvents"; import { MapEvents } from "@/components/MapEvents";
const center: LatLngLiteral = { lat: 47.0844, lng: 2.3964 }; const center: LatLngLiteral = { lat: 47.0844, lng: 2.3964 };
@@ -73,7 +68,7 @@ export const ZoneEditor = ({ value, onChange }: ZoneEditorProps) => {
onDeleted={handleChange} onDeleted={handleChange}
draw={{ draw={{
rectangle: false, rectangle: false,
circle: true, circle: false,
polyline: false, polyline: false,
polygon: true, polygon: true,
marker: false, marker: false,
+18 -2
View File
@@ -13,7 +13,11 @@
"selectPlaceholder": "Select...", "selectPlaceholder": "Select...",
"searchPlaceholder": "Search...", "searchPlaceholder": "Search...",
"noOptionsMessage": "No options found", "noOptionsMessage": "No options found",
"timeControlEnum": "{tc, select, Classic {Classic} Rapid {Rapid} Blitz {Blitz} Other {Other} other {{tc}}}" "timeControlEnum": "{tc, select, Classic {Classic} Rapid {Rapid} Blitz {Blitz} Other {Other} other {{tc}}}",
"timeControlEnumInline": "{tc, select, Classic {classic} Rapid {rapid} Blitz {blitz} Other {other} other {{tc}}}",
"saveButton": "Save",
"cancelButton": "Cancel"
}, },
"Errors": { "Errors": {
@@ -230,10 +234,22 @@
}, },
"Zones": { "Zones": {
"title": "Your Zones",
"info": "You can set up zones to receive email notifications for tournaments in these areas. These zones can also be used to filter tournaments on the main map.",
"noNotifications": "You have not enabled email notifications for this zone.",
"withNotifications": "You will receive email notifications for new tournaments with <b>{list}</b> time control in this region.",
"editButton": "Edit",
"deleteButton": "Delete",
"addZoneButton": "Add a Region",
"createTitle": "Create a new zone",
"zoneNameLabel": "Zone name", "zoneNameLabel": "Zone name",
"zoneNamePlaceholder": "Name for your zone", "zoneNamePlaceholder": "Name for your zone",
"notificationsLabel": "Notifications", "notificationsLabel": "Notifications",
"notificationsInfo": "You can choose to turn on notifications for the time controls that interest you, and will receive an email when a new tournament is added to this zone.", "notificationsInfo": "You can choose to turn on notifications for the time controls that interest you, and will receive an email when a new tournament is added to this zone.",
"saveButton": "Save" "saveButton": "Save",
"createFailure": "Oops, something went wrong. Please try again later."
} }
} }
+20 -4
View File
@@ -13,7 +13,11 @@
"selectPlaceholder": "Choisir...", "selectPlaceholder": "Choisir...",
"searchPlaceholder": "Rechercher...", "searchPlaceholder": "Rechercher...",
"noOptionsMessage": "Pas d'options", "noOptionsMessage": "Pas d'options",
"timeControlEnum": "{tc, select, Classic {Cadence Lente} Rapid {Rapide} Blitz {Blitz} Other {Autres} other {{tc}}}" "timeControlEnum": "{tc, select, Classic {Cadence Lente} Rapid {Rapide} Blitz {Blitz} Other {Autres} other {{tc}}}",
"timeControlEnumInline": "{tc, select, Classic {lente} Rapid {rapide} Blitz {blitz} Other {autres} other {{tc}}}",
"saveButton": "Sauvegarder",
"cancelButton": "Annuler"
}, },
"Errors": { "Errors": {
@@ -231,10 +235,22 @@
}, },
"Zones": { "Zones": {
"zoneNameLabel": "Nom de la zone", "title": "Vos régions",
"zoneNamePlaceholder": "Votre nom pour la zone", "info": "Vous pouvez définir des zones personnalisées pour recevoir des notifications par e-mail pour les tournois dans ces zones. Ces zones peuvent aussi être utiliser pour filtrer les tournois sur la carte.",
"noNotifications": "Vous n'avez pas activé les notifications par email pour cette région.",
"withNotifications": "Vous allez recevoir des notifications par e-mail pour les nouveaux tournois de cadences <b>{list}</b> dans cette région.",
"editButton": "Modifier",
"deleteButton": "Supprimer",
"addZoneButton": "Ajouter une région",
"createTitle": "Créer une nouvelle région",
"zoneNameLabel": "Nom de la région",
"zoneNamePlaceholder": "Votre nom pour cette région",
"notificationsLabel": "Notifications", "notificationsLabel": "Notifications",
"notificationsInfo": "Vous pouvez choisir d'activer les notifications pour les cadences qui vous intéressent, et vous recevrez un e-mail lorsqu'un nouveau tournoi est ajouté dans cette zone.", "notificationsInfo": "Vous pouvez choisir d'activer les notifications pour les cadences qui vous intéressent, et vous recevrez un e-mail lorsqu'un nouveau tournoi est ajouté dans cette zone.",
"saveButton": "Sauvegarder" "saveButton": "Sauvegarder",
"createFailure": "Oups, quelque chose s'est mal passé. Veuillez réessayer."
} }
} }
+14
View File
@@ -1,3 +1,4 @@
import { zu } from "@infra-blocks/zod-utils";
import { z } from "zod"; import { z } from "zod";
import { TimeControl } from "@/types"; import { TimeControl } from "@/types";
@@ -30,3 +31,16 @@ export const addTournamentSchema = z.object({
export const fetchTournamentResultsSchema = z.object({ export const fetchTournamentResultsSchema = z.object({
id: z.string().min(1, { message: "FormValidation.required" }), id: z.string().min(1, { message: "FormValidation.required" }),
}); });
export const zoneSchema = z
.object({
name: z.string().min(1, { message: "FormValidation.required" }),
features: zu.geojson.featureCollection(),
classicNotifications: z.boolean(),
rapidNotifications: z.boolean(),
blitzNotifications: z.boolean(),
})
.refine((data) => data.features.features.length > 0, {
message: "FormValidation.zone",
path: ["features"],
});
+34
View File
@@ -0,0 +1,34 @@
"use server";
import { ObjectId } from "mongodb";
import { auth } from "@/auth";
import { zoneSchema } from "@/schemas";
import { collections, dbConnect } from "@/server/mongodb";
import { errorLog } from "@/utils/logger";
import { ZoneModel } from "./models/zoneModel";
import { action } from "./safeAction";
export const createZone = action(zoneSchema, 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 zoneData: ZoneModel = {
...input,
userId: new ObjectId(user.user!.id!),
};
const result = await collections.zones!.insertOne(zoneData);
return true;
} catch (error) {
errorLog(error);
throw error;
}
});
+14
View File
@@ -0,0 +1,14 @@
import { zu } from "@infra-blocks/zod-utils";
import { ObjectId } from "mongodb";
import { z } from "zod";
const featureCollection = zu.geojson.featureCollection();
export type ZoneModel = {
userId: ObjectId;
name: string;
classicNotifications: boolean;
rapidNotifications: boolean;
blitzNotifications: boolean;
features: z.infer<typeof featureCollection>;
};
+2
View File
@@ -10,6 +10,7 @@ export const collections: {
tournaments?: mongoDB.Collection<TournamentModel>; tournaments?: mongoDB.Collection<TournamentModel>;
clubs?: mongoDB.Collection<ClubModel>; clubs?: mongoDB.Collection<ClubModel>;
users?: mongoDB.Collection<UserModel>; users?: mongoDB.Collection<UserModel>;
zones?: mongoDB.Collection<ZoneModel>;
} = {}; } = {};
if (!process.env.MONGODB_URI) { if (!process.env.MONGODB_URI) {
@@ -34,6 +35,7 @@ export async function dbConnect() {
const userData: mongoDB.Db = client!.db("userData"); const userData: mongoDB.Db = client!.db("userData");
collections.users = userData.collection("userData"); collections.users = userData.collection("userData");
collections.zones = userData.collection("zones");
const tournamentData: mongoDB.Db = client!.db("tournamentsFranceDB"); const tournamentData: mongoDB.Db = client!.db("tournamentsFranceDB");
collections.tournaments = tournamentData.collection("tournaments"); collections.tournaments = tournamentData.collection("tournaments");
+29
View File
@@ -0,0 +1,29 @@
"use server";
import { omit } from "lodash";
import { ObjectId } from "mongodb";
import { z } from "zod";
import { auth } from "@/auth";
import { collections, dbConnect } from "@/server/mongodb";
import { action } from "./safeAction";
export const myZones = action(z.void(), async () => {
await dbConnect();
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to fetch your zones");
}
const zones = await collections
.zones!.find({ userId: new ObjectId(user.user!.id!) })
.toArray();
return zones.map((zone) => ({
...omit(zone, ["_id"]),
id: zone._id.toString(),
userId: zone.userId.toString(),
}));
});
+10
View File
@@ -17,6 +17,16 @@ export const pathnames = {
en: "/tournaments", en: "/tournaments",
}, },
"/zones": {
fr: "/regions",
en: "/zones",
},
"/zones/create": {
fr: "/regions/creer",
en: "/zones/create",
},
"/add-tournament": { "/add-tournament": {
fr: "/ajouter-un-tournoi", fr: "/ajouter-un-tournoi",
en: "/add-tournament", en: "/add-tournament",
+5
View File
@@ -0,0 +1,5 @@
// To disable all workbox logging during development, you can set self.__WB_DISABLE_DEV_LOGS to true
// https://developers.google.com/web/tools/workbox/guides/configure-workbox#disable_logging
// eslint-disable-next-line no-underscore-dangle,no-restricted-globals
self.__WB_DISABLE_DEV_LOGS = true;