Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@ COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80

CMD sh -c "nginx && cd /app/server && node dist/server.js"
WORKDIR /app/server

CMD ["sh", "start.sh"]
64 changes: 52 additions & 12 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@ import mascotSit from "./assets/icons/umsa_sit.png";
import mascotCap from "./assets/icons/umsa_cool.png";
import heroPhoto from "./assets/humans.png";

const DEFAULTS = {
heading: "WELCOME TO UMSA",
subtitle: "The union of Malaysian students in Auckland.",
aboutHeading: "WHAT IS UMSA?",
aboutBody: "",
introVideoUrl: "",
};

const HERO_FOOT =
"Non-profit Malaysian student-run club affiliated with the University of Auckland, New Zealand.";

Expand Down Expand Up @@ -113,14 +105,46 @@ function Hero({ heading, subtitle }: { heading: string; subtitle: string }) {
}

export default function App() {
const { data } = useHomeContent();
const { data: events } = useEvents();
const content = { ...DEFAULTS, ...(data ?? {}) };
const { data: content, isPending, isFetching, refetch } = useHomeContent();
const {
data: events,
isPending: eventsPending,
isError: eventsError,
refetch: refetchEvents,
isFetching: eventsFetching,
} = useEvents();

useEffect(() => {
document.title = "UMSA — Home";
}, []);

if (isPending) {
return (
<section
className="mx-auto max-w-4xl px-6 py-20 text-center"
role="status"
>
Loading homepage…
</section>
);
}

if (!content) {
return (
<section className="mx-auto max-w-4xl px-6 py-20 text-center">
<p role="alert">We couldn’t load the homepage. Please try again.</p>
<button
type="button"
onClick={() => void refetch()}
disabled={isFetching}
className="mt-4 rounded-full bg-accent1-primary px-6 py-3 text-white disabled:opacity-50"
>
{isFetching ? "Loading…" : "Try again"}
</button>
</section>
);
}

const upcoming = (events ?? [])
.map((e) => ({ ...e, isDone: new Date(e.eventDate) < new Date() }))
.filter((e) => !e.isDone)
Expand Down Expand Up @@ -234,7 +258,23 @@ export default function App() {
</h2>
</div>

<EventCarousel events={upcoming} />
{eventsPending ? (
<p role="status">Loading events…</p>
) : eventsError && !events ? (
<div>
<p role="alert">We couldn’t load the events.</p>
<button
type="button"
onClick={() => void refetchEvents()}
disabled={eventsFetching}
className="mt-3 underline disabled:opacity-50"
>
{eventsFetching ? "Loading…" : "Try again"}
</button>
</div>
) : (
<EventCarousel events={upcoming} />
)}

<div className="mt-10 text-center">
<a
Expand Down
13 changes: 8 additions & 5 deletions client/src/hooks/useCollection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isAxiosError } from "axios";
import { api } from "../lib/api";
import { api, publicReadOptions } from "../lib/api";
import { ME_KEY } from "./useAuth";

export type Collection = "members" | "events" | "sponsors" | "gallery" | "faqs";
Expand All @@ -9,17 +9,19 @@ export const collectionKey = (name: Collection) => [name] as const;

export function useCollection<T>(name: Collection) {
return useQuery({
...publicReadOptions,
queryKey: collectionKey(name),
queryFn: () => api.get<T[]>(`/${name}`).then((res) => res.data),
queryFn: ({ signal }) =>
api.get<T[]>(`/${name}`, { timeout: 10000, signal }).then((res) => res.data),
});
}

function useInvalidate(name: Collection) {
const queryClient = useQueryClient();
return {
onSuccess: () => queryClient.invalidateQueries({ queryKey: collectionKey(name) }),
onSuccess: () =>
queryClient.invalidateQueries({ queryKey: collectionKey(name) }),
onError: (err: unknown) => {

if (isAxiosError(err) && err.response?.status === 401) {
queryClient.setQueryData(ME_KEY, null);
}
Expand All @@ -45,7 +47,8 @@ export function useUpdate<T extends { id: string }>(name: Collection) {

export function useRemove(name: Collection) {
return useMutation({
mutationFn: (id: string) => api.delete(`/admin/${name}/${id}`).then((res) => res.data),
mutationFn: (id: string) =>
api.delete(`/admin/${name}/${id}`).then((res) => res.data),
...useInvalidate(name),
});
}
20 changes: 14 additions & 6 deletions client/src/hooks/useHomeContent.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isAxiosError } from "axios";
import { api } from "../lib/api";
import { api, publicReadOptions } from "../lib/api";
import { ME_KEY } from "./useAuth";
import type { HomeContentValues } from "../schemas/content";

export const HOME_CONTENT_KEY = ["content", "home"] as const;

export function useHomeContent() {
return useQuery({
...publicReadOptions,
queryKey: HOME_CONTENT_KEY,
queryFn: () => api.get<HomeContentValues>("/content/home").then((res) => res.data),
queryFn: ({ signal }) =>
api
.get<HomeContentValues>("/content/home", { timeout: 10000, signal })
.then((res) => res.data),
});
}

export function useSaveHomeContent() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (values: HomeContentValues) =>
api.put<HomeContentValues>("/admin/content/home", values).then((res) => res.data),
// forces refetch so every render sees the new values
onSuccess: () => queryClient.invalidateQueries({ queryKey: HOME_CONTENT_KEY }),
api
.put<HomeContentValues>("/admin/content/home", values)
.then((res) => res.data),
onSuccess: async (values) => {
queryClient.setQueryData(HOME_CONTENT_KEY, values);
await queryClient.invalidateQueries({ queryKey: HOME_CONTENT_KEY });
},
onError: (err) => {
if (isAxiosError(err) && err.response?.status === 401) {
// session died mid-edit -> nulls auth cache and AdminLayout redirects
// session died mid-edit -> nulls auth cache and AdminLayout redirects
queryClient.setQueryData(ME_KEY, null);
}
},
Expand Down
10 changes: 10 additions & 0 deletions client/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,13 @@ export function apiErrorMessage(err: unknown): string {
}
return "Something went wrong";
}

export const publicReadOptions = {
retry: (failureCount: number, error: Error) => {
if (failureCount >= 3) return false;
if (!isAxiosError(error)) return false;
const status = error.response?.status;
return !status || status === 408 || status === 429 || status >= 500;
},
retryDelay: (attempt: number) => Math.min(1000 * 2 ** attempt, 4000),
};
9 changes: 8 additions & 1 deletion fly.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ primary_region = "syd"
auto_start_machines = true
min_machines_running = 0

[[http_service.checks]]
grace_period = "10s"
interval = "15s"
method = "GET"
timeout = "5s"
path = "/api/health"

[[vm]]
memory = "256mb"
cpu_kind = "shared"
cpus = 1
cpus = 1
4 changes: 4 additions & 0 deletions server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ app.use(
);
app.use(express.json({ limit: process.env.JSON_BODY_LIMIT || "1mb" }));
app.use(cookieParser());
app.use("/api", (_req, res, next) => {
res.set("Cache-Control", "no-store");
next();
});
app.use("/api", apiRateLimit);
app.use("/api/health", healthRoutes);

Expand Down
18 changes: 13 additions & 5 deletions server/src/routes/health.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import { Router } from "express";
import mongoose from "mongoose";

const router = Router();

router.get("/", (_req, res) => {
res.json({
status: "ok",
service: "umsa-api",
});
router.get("/", async (_req, res) => {
const db = mongoose.connection.db;
if (mongoose.connection.readyState !== 1 || !db) {
return res.status(503).json({ status: "unavailable", service: "umsa-api" });
}

try {
await db.command({ ping: 1 }, { timeoutMS: 2000 });
res.json({ status: "ok", service: "umsa-api" });
} catch {
res.status(503).json({ status: "unavailable", service: "umsa-api" });
}
});

export default router;
34 changes: 34 additions & 0 deletions server/start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/bin/sh
set -eu

node dist/server.js &
api_pid=$!
nginx_pid=""

cleanup() {
kill "$api_pid" ${nginx_pid:+"$nginx_pid"} 2>/dev/null || true
}
trap cleanup EXIT
trap 'exit 143' TERM
trap 'exit 130' INT

attempt=0
until wget -q -T 2 -O /dev/null http://127.0.0.1:5050/api/health; do
if ! kill -0 "$api_pid" 2>/dev/null; then
wait "$api_pid"
exit 1
fi
attempt=$((attempt + 1))
if [ "$attempt" -ge 30 ]; then
echo "API did not become ready" >&2
exit 1
fi
sleep 1
done

nginx -g 'daemon off;' &
nginx_pid=$!
while kill -0 "$api_pid" 2>/dev/null && kill -0 "$nginx_pid" 2>/dev/null; do
sleep 1
done
exit 1
Loading