forge
Explore
Log in

Don't you dare go Hollow

✨ add typed API client, session auth, and shared helpers

Browse files at this commit

c3fc1e3040b0af7fd23433de4f78f0ddda366a14Ahmet Kaan GümüşParent: 394614a
  • feat
    • ✨ add typed API client, session auth, and shared helpers
Show full message
feat: ✨ add typed API client, session auth, and shared helpers

Core plumbing every page builds on:

- types.ts mirrors the backend DTOs and validation limits, with the
  role ladder and the atLeast() privilege check
- api.ts wraps every endpoint over one request primitive; failures
  throw ApiError carrying the backend message, status, and Retry-After
- auth.tsx fetches /auth/me once and mutates the session resource in
  place on login/register/logout; exposes can(role) for gating UI
- action.ts wraps mutations with pending/error signals for forms
- format.ts converts between unix milliseconds and datetime-local
src/lib/action.tsadded+49 -0
@@ -0,0 +1,49 @@
1+// Tiny mutation helper: wraps an async action with pending/error signals so
2+// forms get busy-state and failure display without repeating try/catch.
3+
4+import { batch, createSignal, type Accessor } from "solid-js";
5+import { ApiError } from "./api";
6+
7+export interface Action<Args extends unknown[]> {
8+ run: (...args: Args) => Promise<boolean>;
9+ pending: Accessor<boolean>;
10+ error: Accessor<string | null>;
11+ clearError: () => void;
12+}
13+
14+export function createAction<Args extends unknown[]>(
15+ action: (...args: Args) => Promise<void>,
16+): Action<Args> {
17+ const [pending, setPending] = createSignal(false);
18+ const [error, setError] = createSignal<string | null>(null);
19+
20+ return {
21+ pending,
22+ error,
23+ clearError: () => setError(null),
24+ run: async (...args) => {
25+ batch(() => {
26+ setPending(true);
27+ setError(null);
28+ });
29+ try {
30+ await action(...args);
31+ return true;
32+ } catch (err) {
33+ setError(describe(err));
34+ return false;
35+ } finally {
36+ setPending(false);
37+ }
38+ },
39+ };
40+}
41+
42+function describe(err: unknown): string {
43+ if (err instanceof ApiError) {
44+ return err.retryAfterSecs !== undefined
45+ ? `${err.message} — retry in ${err.retryAfterSecs}s`
46+ : err.message;
47+ }
48+ return err instanceof Error ? err.message : "something went wrong";
49+}
src/lib/api.tsadded+175 -0
@@ -0,0 +1,175 @@
1+// Typed HTTP client for the Hezarfen backend. One `request` primitive, then a
2+// thin endpoint map per resource. Failures always throw `ApiError` carrying the
3+// backend's `{ "error": "..." }` message and the HTTP status.
4+
5+import type {
6+ AppEvent,
7+ Attendance,
8+ AttendanceStatus,
9+ Course,
10+ Enrollment,
11+ Exam,
12+ ExamResult,
13+ ExamStatistics,
14+ MarksReport,
15+ Note,
16+ Role,
17+ User,
18+} from "./types";
19+
20+const BASE = import.meta.env.VITE_API_URL ?? "/api";
21+
22+export class ApiError extends Error {
23+ constructor(
24+ readonly status: number,
25+ message: string,
26+ readonly retryAfterSecs?: number,
27+ ) {
28+ super(message);
29+ this.name = "ApiError";
30+ }
31+}
32+
33+async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
34+ let res: Response;
35+ try {
36+ res = await fetch(BASE + path, {
37+ method,
38+ credentials: "include",
39+ headers: body === undefined ? undefined : { "content-type": "application/json" },
40+ body: body === undefined ? undefined : JSON.stringify(body),
41+ });
42+ } catch {
43+ throw new ApiError(0, "network error — is the backend up?");
44+ }
45+
46+ if (!res.ok) {
47+ let message = res.statusText.toLowerCase() || "request failed";
48+ try {
49+ message = ((await res.json()) as { error: string }).error;
50+ } catch {
51+ // Non-JSON error body; keep the status text.
52+ }
53+ const retryAfter = Number(res.headers.get("retry-after"));
54+ throw new ApiError(res.status, message, Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined);
55+ }
56+
57+ return res.status === 204 ? (undefined as T) : res.json();
58+}
59+
60+const get = <T>(path: string) => request<T>("GET", path);
61+const post = <T>(path: string, body?: unknown) => request<T>("POST", path, body);
62+const patch = <T>(path: string, body: unknown) => request<T>("PATCH", path, body);
63+const del = (path: string) => request<void>("DELETE", path);
64+
65+export interface Credentials {
66+ username: string;
67+ password: string;
68+}
69+
70+export const auth = {
71+ me: () => get<User>("/auth/me"),
72+ register: (credentials: Credentials) => post<User>("/auth/register", credentials),
73+ login: (credentials: Credentials) => post<User>("/auth/login", credentials),
74+ logout: () => post<void>("/auth/logout"),
75+};
76+
77+/** Partial profile update: omit a field to keep it, send `""` to clear it. */
78+export interface ProfilePatch {
79+ name?: string;
80+ surname?: string;
81+ email?: string;
82+ phone?: string;
83+ /** `YYYY-MM-DD`. */
84+ birth_date?: string;
85+}
86+
87+export const users = {
88+ list: () => get<User[]>("/users"),
89+ get: (id: string) => get<User>(`/users/${id}`),
90+ setRole: (id: string, role: Role) => patch<User>(`/users/${id}/role`, { role }),
91+ /** The caller's own profile. */
92+ updateMyProfile: (body: ProfilePatch) => patch<User>("/users/me", body),
93+ /** Any user's profile; admin only. */
94+ updateProfile: (id: string, body: ProfilePatch) => patch<User>(`/users/${id}/profile`, body),
95+};
96+
97+export const notes = {
98+ list: () => get<Note[]>("/notes"),
99+ create: (body: { title: string; content?: string }) => post<Note>("/notes", body),
100+ update: (id: string, body: { title?: string; content?: string }) =>
101+ patch<Note>(`/notes/${id}`, body),
102+ remove: (id: string) => del(`/notes/${id}`),
103+};
104+
105+export const events = {
106+ list: () => get<AppEvent[]>("/events"),
107+ get: (id: string) => get<AppEvent>(`/events/${id}`),
108+ create: (body: {
109+ title: string;
110+ description?: string;
111+ starts_at?: number;
112+ ends_at?: number;
113+ }) => post<AppEvent>("/events", body),
114+ /** `null` clears a timestamp; omitting a field keeps it. */
115+ update: (
116+ id: string,
117+ body: {
118+ title?: string;
119+ description?: string;
120+ starts_at?: number | null;
121+ ends_at?: number | null;
122+ },
123+ ) => patch<AppEvent>(`/events/${id}`, body),
124+ remove: (id: string) => del(`/events/${id}`),
125+
126+ attendance: (id: string) => get<Attendance[]>(`/events/${id}/attendance`),
127+ mark: (id: string, status: AttendanceStatus, userId?: string) =>
128+ post<Attendance>(`/events/${id}/attendance`, { status, user_id: userId }),
129+ unmark: (id: string, userId: string) => del(`/events/${id}/attendance/${userId}`),
130+};
131+
132+export const courses = {
133+ list: () => get<Course[]>("/courses"),
134+ /** The caller's enrolled courses. */
135+ mine: () => get<Course[]>("/courses/me"),
136+ get: (id: string) => get<Course>(`/courses/${id}`),
137+ create: (body: { title: string; description?: string }) => post<Course>("/courses", body),
138+ update: (id: string, body: { title?: string; description?: string }) =>
139+ patch<Course>(`/courses/${id}`, body),
140+ remove: (id: string) => del(`/courses/${id}`),
141+
142+ roster: (id: string) => get<Enrollment[]>(`/courses/${id}/enrollments`),
143+ enroll: (id: string, userId: string) =>
144+ post<Enrollment>(`/courses/${id}/enrollments`, { user_id: userId }),
145+ unenroll: (id: string, userId: string) => del(`/courses/${id}/enrollments/${userId}`),
146+
147+ exams: (id: string) => get<Exam[]>(`/courses/${id}/exams`),
148+ createExam: (
149+ id: string,
150+ body: { title: string; description?: string; kind: string; weight: number },
151+ ) => post<Exam>(`/courses/${id}/exams`, body),
152+};
153+
154+export const exams = {
155+ list: () => get<Exam[]>("/exams"),
156+ get: (id: string) => get<Exam>(`/exams/${id}`),
157+ // Creation lives under the course: `courses.createExam`.
158+ update: (
159+ id: string,
160+ body: { title?: string; description?: string; kind?: string; weight?: number },
161+ ) => patch<Exam>(`/exams/${id}`, body),
162+ remove: (id: string) => del(`/exams/${id}`),
163+
164+ results: (id: string) => get<ExamResult[]>(`/exams/${id}/results`),
165+ myResult: (id: string) => get<ExamResult>(`/exams/${id}/result`),
166+ grade: (id: string, userId: string, mark: number) =>
167+ post<ExamResult>(`/exams/${id}/results`, { mark, user_id: userId }),
168+ removeResult: (id: string, userId: string) => del(`/exams/${id}/results/${userId}`),
169+ statistics: (id: string) => get<ExamStatistics>(`/exams/${id}/statistics`),
170+};
171+
172+export const marks = {
173+ mine: () => get<MarksReport>("/marks/me"),
174+ forUser: (id: string) => get<MarksReport>(`/marks/${id}`),
175+};
src/lib/auth.tsxadded+71 -0
@@ -0,0 +1,71 @@
1+// Session state for the whole app. `/auth/me` is fetched exactly once at
2+// startup; login/register/logout mutate the resource in place from the
3+// server's response, so every consumer updates instantly with no refetch.
4+
5+import {
6+ createContext,
7+ createResource,
8+ useContext,
9+ type Accessor,
10+ type ParentProps,
11+} from "solid-js";
12+import { ApiError, auth, type Credentials } from "./api";
13+import { atLeast, type Role, type User } from "./types";
14+
15+interface AuthValue {
16+ /** `undefined` while the initial /auth/me is in flight, `null` when logged out. */
17+ user: Accessor<User | null | undefined>;
18+ login: (credentials: Credentials) => Promise<void>;
19+ register: (credentials: Credentials) => Promise<void>;
20+ logout: () => Promise<void>;
21+ /** Replace the session user with a fresh server response (e.g. a profile save). */
22+ update: (user: User) => void;
23+ /** True when the current user's role is `required` or higher. */
24+ can: (required: Role) => boolean;
25+}
26+
27+const AuthContext = createContext<AuthValue>();
28+
29+async function fetchMe(): Promise<User | null> {
30+ try {
31+ return await auth.me();
32+ } catch (err) {
33+ if (err instanceof ApiError && err.status === 401) return null;
34+ throw err;
35+ }
36+}
37+
38+export function AuthProvider(props: ParentProps) {
39+ const [me, { mutate }] = createResource(fetchMe);
40+
41+ const value: AuthValue = {
42+ user: () => (me.state === "ready" ? me() : me.latest ?? undefined),
43+ login: async (credentials) => {
44+ mutate(await auth.login(credentials));
45+ },
46+ register: async (credentials) => {
47+ // Register does not set a session cookie; log in right after.
48+ await auth.register(credentials);
49+ mutate(await auth.login(credentials));
50+ },
51+ logout: async () => {
52+ await auth.logout();
53+ mutate(null);
54+ },
55+ update: (user) => {
56+ mutate(user);
57+ },
58+ can: (required) => {
59+ const current = me.latest;
60+ return current != null && atLeast(current.role, required);
61+ },
62+ };
63+
64+ return <AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>;
65+}
66+
67+export function useAuth(): AuthValue {
68+ const value = useContext(AuthContext);
69+ if (!value) throw new Error("useAuth must be used inside <AuthProvider>");
70+ return value;
71+}
src/lib/format.tsadded+42 -0
@@ -0,0 +1,42 @@
1+// Time helpers: the API speaks unix milliseconds, <input type="datetime-local">
2+// speaks "YYYY-MM-DDTHH:mm" in local time.
3+
4+const formatter = new Intl.DateTimeFormat(undefined, {
5+ dateStyle: "medium",
6+ timeStyle: "short",
7+});
8+
9+export function formatMillis(millis: number | null): string {
10+ return millis === null ? "—" : formatter.format(new Date(millis));
11+}
12+
13+/** Human line for an event's time window. */
14+export function formatWindow(starts: number | null, ends: number | null): string {
15+ if (starts === null && ends === null) return "Unscheduled";
16+ if (starts !== null && ends !== null)
17+ return `${formatMillis(starts)} → ${formatMillis(ends)}`;
18+ return starts !== null ? formatMillis(starts) : `Until ${formatMillis(ends)}`;
19+}
20+
21+/** Unix ms → value for a datetime-local input ("" when null). */
22+export function toInputValue(millis: number | null): string {
23+ if (millis === null) return "";
24+ const date = new Date(millis);
25+ const pad = (n: number) => String(n).padStart(2, "0");
26+ return (
27+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
28+ `T${pad(date.getHours())}:${pad(date.getMinutes())}`
29+ );
30+}
31+
32+/** datetime-local input value → unix ms, null when empty. */
33+export function fromInputValue(value: string): number | null {
34+ return value === "" ? null : new Date(value).getTime();
35+}
36+
37+/** The local date as "YYYY-MM-DD" — e.g. the max for a birth-date input. */
38+export function today(): string {
39+ const date = new Date();
40+ const pad = (n: number) => String(n).padStart(2, "0");
41+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
42+}
src/lib/types.tsadded+149 -0
@@ -0,0 +1,149 @@
1+// Wire types and validation limits, mirroring the backend's DTOs and
2+// `constant.rs`. Keep these in sync with hezarfen_backend.
3+
4+export type Role = "student" | "teacher" | "manager" | "admin";
5+
6+/** Privilege order, lowest to highest — index = rank. */
7+export const ROLES: readonly Role[] = ["student", "teacher", "manager", "admin"];
8+
9+export function atLeast(role: Role, required: Role): boolean {
10+ return ROLES.indexOf(role) >= ROLES.indexOf(required);
11+}
12+
13+export interface User {
14+ id: string;
15+ username: string;
16+ role: Role;
17+ /** Personal info — null until filled in. `birth_date` is `YYYY-MM-DD`. */
18+ name: string | null;
19+ surname: string | null;
20+ email: string | null;
21+ phone: string | null;
22+ birth_date: string | null;
23+}
24+
25+export interface Note {
26+ id: string;
27+ title: string;
28+ content: string;
29+}
30+
31+export interface AppEvent {
32+ id: string;
33+ creator: string;
34+ title: string;
35+ description: string;
36+ /** Unix milliseconds, or null when unscheduled. */
37+ starts_at: number | null;
38+ ends_at: number | null;
39+}
40+
41+export const ATTENDANCE_STATUSES = ["present", "absent", "late", "excused"] as const;
42+export type AttendanceStatus = (typeof ATTENDANCE_STATUSES)[number];
43+
44+export interface Attendance {
45+ id: string;
46+ event: string;
47+ user: string;
48+ status: AttendanceStatus;
49+ marked_by: string;
50+}
51+
52+export interface Course {
53+ id: string;
54+ creator: string;
55+ title: string;
56+ description: string;
57+}
58+
59+export interface Enrollment {
60+ id: string;
61+ course: string;
62+ user: string;
63+ enrolled_by: string;
64+}
65+
66+/** Informational metadata only — `weight` drives the course average. */
67+export const EXAM_KINDS = [
68+ "homework",
69+ "quiz",
70+ "midterm",
71+ "final",
72+ "project",
73+ "oral",
74+] as const;
75+export type ExamKind = (typeof EXAM_KINDS)[number];
76+
77+export interface Exam {
78+ id: string;
79+ creator: string;
80+ course: string;
81+ title: string;
82+ description: string;
83+ kind: ExamKind;
84+ /** Counts `weight` times into the course average, 1–100. */
85+ weight: number;
86+}
87+
88+export interface ExamResult {
89+ id: string;
90+ exam: string;
91+ user: string;
92+ /** 0–100 inclusive. */
93+ mark: number;
94+ graded_by: string;
95+}
96+
97+export interface ExamStatistics {
98+ exam: string;
99+ /** Number of graded results. */
100+ graded: number;
101+ /** Plain mean of the graded marks; null while nothing is graded. */
102+ average: number | null;
103+ min: number | null;
104+ max: number | null;
105+}
106+
107+/** One graded exam inside a course block of the marks report. */
108+export interface MarkEntry {
109+ exam: string;
110+ title: string;
111+ kind: ExamKind;
112+ weight: number;
113+ mark: number;
114+ graded_by: string;
115+}
116+
117+export interface CourseMarks {
118+ course: Course;
119+ /** Graded results only — ungraded exams don't appear. */
120+ results: MarkEntry[];
121+ /** Σ(mark×weight) / Σ(weight); null while nothing is graded. */
122+ average: number | null;
123+}
124+
125+export interface MarksReport {
126+ user: string;
127+ courses: CourseMarks[];
128+ /** Plain mean of the non-null course averages; null while none exist. */
129+ overall_average: number | null;
130+}
131+
132+export const LIMITS = {
133+ username: { min: 3, max: 32 },
134+ password: { min: 6, max: 128 },
135+ personName: 100,
136+ email: 254,
137+ /** Digit count; a leading `+`, spaces, dashes, and parentheses are allowed. */
138+ phoneDigits: { min: 7, max: 15 },
139+ noteTitle: 200,
140+ noteContent: 10_000,
141+ eventTitle: 200,
142+ eventDescription: 2_000,
143+ examTitle: 200,
144+ examDescription: 2_000,
145+ courseTitle: 200,
146+ courseDescription: 2_000,
147+ mark: { min: 0, max: 100 },
148+ weight: { min: 1, max: 100 },
149+} as const;