Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
53325d8
feat: frontend api service
tGiech22 Oct 11, 2025
6f7a536
Merge branch 'main' of https://github.com/GenerateNU/cinecircle into …
tGiech22 Oct 11, 2025
d9a8814
chore: saving changes
tGiech22 Oct 15, 2025
1b14c1e
Chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 Oct 15, 2025
5550b4a
Ratings type
abby-stevenson Oct 1, 2025
8491ab1
Adding Rating to schema
abby-stevenson Oct 1, 2025
9b10360
Adding the create new rating
abby-stevenson Oct 1, 2025
fdd2d98
update to ratings
abby-stevenson Oct 1, 2025
98fe676
middleware
abby-stevenson Oct 2, 2025
6bd44c8
Deleting fake middleware
abby-stevenson Oct 10, 2025
af569d4
Adding tests
abby-stevenson Oct 10, 2025
676f665
Adding votes and removing double rating
abby-stevenson Oct 10, 2025
ef59c56
Rest of Crud
abby-stevenson Oct 13, 2025
8084d31
Fix: Add /api prefix in routes/index.ts
danctila Oct 13, 2025
62eb249
Fix: Check for Authorization header in auth mocks
danctila Oct 13, 2025
2eaa444
Fix: remove threadedComments from rating creation
danctila Oct 13, 2025
00fb691
fix: adding mapping functions
tGiech22 Oct 16, 2025
d0928ed
Merge branch 'main' of https://github.com/GenerateNU/cinecircle into …
tGiech22 Oct 16, 2025
45a944c
Merge branch 'main' of https://github.com/GenerateNU/cinecircle into …
tGiech22 Oct 16, 2025
00de2f8
saving changes
tGiech22 Oct 16, 2025
9f2b25e
chore: resolving merge conflicts
tGiech22 Oct 20, 2025
836b984
chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 Oct 29, 2025
6f2aefb
fix: adding mapping functions to tmdb.ts
tGiech22 Oct 30, 2025
a12d486
fix: this schema.prisma file seems to work
tGiech22 Oct 30, 2025
34fb614
chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 Oct 30, 2025
0a4aef3
fix: adding mapping functions for user.ts
tGiech22 Oct 30, 2025
aba6618
saving changes
tGiech22 Oct 31, 2025
0cf77f5
refactor: redoing mapping functions
tGiech22 Oct 31, 2025
8907c3e
fix: deleting unnecessary model
tGiech22 Nov 2, 2025
6ac0f03
fix: added mapping function for movies and tests
tGiech22 Nov 2, 2025
c5eca2a
fix: fixing import paths
tGiech22 Nov 2, 2025
dac6546
fix: adding mapping functions for user.ts and userFollows.ts
tGiech22 Nov 2, 2025
b70d20c
fix: changing imdbRating to BigInt for a test in movie.api.tests
tGiech22 Nov 2, 2025
6920c66
chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 Nov 2, 2025
e049fdb
fix: removing unnecessary mapper and tests for movie
tGiech22 Nov 2, 2025
e9e40e2
fix: fixing import for movie unit tests
tGiech22 Nov 2, 2025
4437b2a
fix: fixing mapping function usage
tGiech22 Nov 2, 2025
aa943b9
adding tests for userFollows
tGiech22 Nov 2, 2025
85e4c86
fix: fixing mapping function of tmdb
tGiech22 Nov 3, 2025
208c613
fix: fixing movie unit tests
tGiech22 Nov 3, 2025
82ee106
fix: fixing tests
tGiech22 Nov 3, 2025
2667012
fix: user schema relation names
danctila Nov 4, 2025
ae42136
fix: rm doc directory
danctila Nov 4, 2025
f76f3e4
Merge branch 'main' into frontend-api-service
danctila Nov 4, 2025
e8e9981
remove chat comments
danctila Nov 4, 2025
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
8 changes: 4 additions & 4 deletions backend/src/controllers/tmdb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ export function mapTmdbToMovie(
.map((l) => l.english_name)
.filter(Boolean) as string[],
imdbRating: Math.round((tmdb.vote_average ?? 0) * 10), // e.g., 7.5 -> 75 (stored as BigInt)
localRating: defaults.localRating ?? "0",
numRatings: defaults.numRatings ?? "0",
localRating: defaults.localRating ?? 0,
numRatings: defaults.numRatings ?? 0,
};
}

Expand Down Expand Up @@ -127,8 +127,8 @@ export const updateMovie = async (req: Request, res: Response) => {
if (description !== undefined) updateData.description = description;
if (languages !== undefined) updateData.languages = languages;
if (imdbRating !== undefined) updateData.imdbRating = imdbRating;
if (localRating !== undefined) updateData.localRating = String(localRating);
if (numRatings !== undefined) updateData.numRatings = String(numRatings);
if (localRating !== undefined) updateData.localRating = Number(localRating);
if (numRatings !== undefined) updateData.numRatings = Number(numRatings);

if (Object.keys(updateData).length === 0) {
return res.status(400).json({ message: "No fields to update" });
Expand Down
190 changes: 190 additions & 0 deletions backend/src/services/apiClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />

import Config from "react-native-config";

/**
* Usage:
* import { api } from "./apiClient";
* const res = await api.get<ApiEnvelope<Movie>>(`/movies/${tmdbId}`);
*/

export type ApiEnvelope<T> = {
message?: string;
data?: T;
[key: string]: unknown;
};

export class ApiError extends Error {
status?: number;
url?: string;
body?: unknown;

constructor(message: string, opts?: { status?: number; url?: string; body?: unknown }) {
super(message);
this.name = "ApiError";
this.status = opts?.status;
this.url = opts?.url;
this.body = opts?.body;
}
}

type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

type ApiClientOptions = {
baseUrl: string;
getToken?: () => string | undefined;
defaultHeaders?: HeadersInit;
timeoutMs?: number;
};

function joinUrl(base: string, path: string) {
const left = base.replace(/\/+$/, "");
const right = path.startsWith("/") ? path : `/${path}`;
return `${left}${right}`;
}

export function toQuery(params?: Record<string, any>): string {
if (!params || Object.keys(params).length === 0) return "";
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === null) continue;
if (Array.isArray(v)) v.forEach((item) => q.append(k, String(item)));
else q.set(k, String(v));
}
const s = q.toString();
return s ? `?${s}` : "";
}

export class ApiClient {
private baseUrl: string;
private getToken?: () => string | undefined;
private defaultHeaders: HeadersInit;
private timeoutMs: number;

constructor(opts: ApiClientOptions) {
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
this.getToken = opts.getToken;
this.defaultHeaders = opts.defaultHeaders ?? {};
this.timeoutMs = opts.timeoutMs ?? 15000;
}

/** Normalize all header inputs to a Headers object. */
private buildHeaders(extra?: HeadersInit, body?: unknown): Headers {
const h = new Headers();

// defaults first
new Headers(this.defaultHeaders).forEach((v, k) => h.set(k, v));
// then per-call extras
if (extra) new Headers(extra).forEach((v, k) => h.set(k, v));

// auth
const token = this.getToken?.();
if (token) h.set("Authorization", `Bearer ${token}`);

// Content-Type for non-FormData bodies
const isForm = typeof FormData !== "undefined" && body instanceof FormData;
if (!isForm && body !== undefined && !h.has("Content-Type")) {
h.set("Content-Type", "application/json");
}

return h;
}

private withTimeout<T>(promise: Promise<T>, ms: number) {
return new Promise<T>((resolve, reject) => {
const id = setTimeout(() => reject(new ApiError(`Request timed out after ${ms}ms`)), ms);
promise.then(
(v) => {
clearTimeout(id);
resolve(v);
},
(e) => {
clearTimeout(id);
reject(e);
},
);
});
}

private async request<T>(
method: HttpMethod,
path: string,
opts?: { body?: unknown; headers?: HeadersInit; signal?: AbortSignal }
): Promise<T> {
const url = joinUrl(this.baseUrl, path);

// Pass FormData through; otherwise JSON.stringify bodies
const isForm = typeof FormData !== "undefined" && opts?.body instanceof FormData;
const bodyInit = isForm
? (opts?.body as BodyInit)
: opts?.body !== undefined
? JSON.stringify(opts.body)
: undefined;

const init: RequestInit = {
method,
headers: this.buildHeaders(opts?.headers, opts?.body),
body: bodyInit,
signal: opts?.signal,
};

const res = await this.withTimeout(fetch(url, init), this.timeoutMs);

const raw = await res.text();
const isJson =
raw &&
(res.headers.get("content-type")?.includes("application/json") ||
raw.trim().startsWith("{") ||
raw.trim().startsWith("["));

let parsed: any = null;
if (raw) {
try {
parsed = isJson ? JSON.parse(raw) : raw;
} catch {
parsed = raw;
}
}

if (!res.ok) {
const message =
(parsed && (parsed.message || parsed.error)) ||
`HTTP ${res.status} ${res.statusText}`;
throw new ApiError(message, { status: res.status, url, body: parsed });
}

return (parsed as T) ?? ({} as T);
}

get<T>(path: string, params?: Record<string, any>, headers?: HeadersInit) {
const qs = toQuery(params);
return this.request<T>("GET", `${path}${qs}`, { headers });
}

post<T>(path: string, body?: unknown, headers?: HeadersInit) {
return this.request<T>("POST", path, { body, headers });
}

put<T>(path: string, body?: unknown, headers?: HeadersInit) {
return this.request<T>("PUT", path, { body, headers });
}

patch<T>(path: string, body?: unknown, headers?: HeadersInit) {
return this.request<T>("PATCH", path, { body, headers });
}

delete<T>(path: string, headers?: HeadersInit) {
return this.request<T>("DELETE", path, { headers });
}
}

const BASE_URL =
Config.API_BASE_URL ||
Comment thread
danctila marked this conversation as resolved.
"http://localhost:3000";

export const api = new ApiClient({
baseUrl: BASE_URL,
getToken: () =>
typeof window !== "undefined" ? localStorage.getItem("token") || undefined : undefined,
});
23 changes: 23 additions & 0 deletions backend/src/services/followService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// src/services/followService.ts
import { api } from "./apiClient";
import type { FollowEdge } from "../types/models";

/** POST /api/user/follow Body: { followingId } */
export function followUser(followingId: string) {
return api.post<{ message: string }>(`/api/user/follow`, { followingId });
}

/** POST /api/user/unfollow Body: { followingId } */
export function unfollowUser(followingId: string) {
return api.post<{ message: string }>(`/api/user/unfollow`, { followingId });
}

/** GET /api/user/:userId/followers -> { followers: Array<{ follower: UserProfile }> } */
export function getFollowers(userId: string) {
return api.get<{ followers: FollowEdge[] }>(`/api/user/${userId}/followers`);
}

/** GET /api/user/:userId/following -> { following: Array<{ following: UserProfile }> } */
export function getFollowing(userId: string) {
return api.get<{ following: FollowEdge[] }>(`/api/user/${userId}/following`);
}
14 changes: 14 additions & 0 deletions backend/src/services/healthService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// src/services/healthService.ts
import { api } from "./apiClient";

export function ping() {
return api.get<{ message?: string; [k: string]: unknown }>(`/api/ping`);
}

export function dbTest() {
return api.get<{ message?: string; [k: string]: unknown }>(`/api/db-test`);
}

export function getSwagger() {
return api.get<any>(`/swagger-output.json`);
}
18 changes: 18 additions & 0 deletions backend/src/services/moviesService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { api } from "./apiClient";
import type { GetMovieEnvelope, UpdateMovieInput, UpdateMovieEnvelope, DeleteMovieResponse } from "../types/apiTypes";

export function fetchAndSaveByTmdbId(tmdbId: string) {
return api.get<GetMovieEnvelope>(`/movies/${tmdbId}`);
}

export function getMovieByCinecircleId(movieId: string) {
return api.get<GetMovieEnvelope>(`/movies/cinecircle/${movieId}`);
}

export function updateMovieByCinecircleId(movieId: string, payload: UpdateMovieInput) {
return api.put<UpdateMovieEnvelope>(`/movies/cinecircle/${movieId}`, payload);
}

export function deleteMovie(movieId: string) {
return api.delete<DeleteMovieResponse>(`/movies/${movieId}`);
}
27 changes: 27 additions & 0 deletions backend/src/services/typedCall.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { api } from "../services/apiClient";
import type { Endpoints } from "../types/endpoints";

type Key = keyof Endpoints;
type Res<K extends Key> = Endpoints[K]["response"];
type Body<K extends Key> = Endpoints[K] extends { body: infer B } ? B : undefined;

export const endpoints: Endpoints = {
"GET /api/ping": { path: () => `/api/ping`, response: {} as any },
} as any;

export async function call<K extends Key>(
key: K,
args: Parameters<Endpoints[K]["path"]>[0],
body?: Body<K>
): Promise<Res<K>> {
const [method,] = (key as string).split(" ") as ["GET"|"POST"|"PUT"|"PATCH"|"DELETE", string];
const path = endpoints[key].path(args as any);

switch (method) {
case "GET": return api.get(path, typeof args === "object" && !Array.isArray(args) ? (args as any) : undefined) as any;
case "DELETE": return api.delete(path) as any;
case "POST": return api.post(path, body) as any;
case "PUT": return api.put(path, body) as any;
case "PATCH": return api.patch(path, body) as any;
}
}
34 changes: 34 additions & 0 deletions backend/src/services/userService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { api } from "./apiClient";
import type {
ProtectedResponse,
GetUserProfileBasicResponse,
UpdateUserProfileInput,
UpdateUserProfileResponse,
DeleteUserProfileResponse,
GetUserRatingsResponse,
GetUserCommentsResponse,
} from "../types/apiTypes";

export function getProtected() {
return api.get<ProtectedResponse>(`/api/protected`);
}

export function getUserProfileBasic() {
return api.get<GetUserProfileBasicResponse>(`/api/user/profile`);
}

export function updateUserProfile(payload: UpdateUserProfileInput) {
return api.put<UpdateUserProfileResponse>(`/api/user/profile`, payload);
}

export function deleteUserProfile() {
return api.delete<DeleteUserProfileResponse>(`/api/user/profile`);
}

export function getUserRatings(userId: string) {
return api.get<GetUserRatingsResponse>(`/api/user/ratings`, { user_id: userId });
}

export function getUserComments(userId: string) {
return api.get<GetUserCommentsResponse>(`/api/user/comments`, { user_id: userId });
}
58 changes: 58 additions & 0 deletions backend/src/types/apiTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { ApiEnvelope } from "../services/apiClient";
import type {
Movie,
UserProfile,
UserProfileBasic,
Rating,
Comment,
FollowEdge,
} from "./models";

/** -------- Health -------- */
export type PingResponse = { message?: string; [k: string]: unknown };
export type DbTestResponse = { message?: string; [k: string]: unknown };

/** -------- Protected -------- */
export type ProtectedResponse = {
message: string;
user: unknown;
timestamp: string;
endpoint: string;
};

/** -------- User Profile Basic (GET /api/user/profile) -------- */
export type GetUserProfileBasicResponse = {
message?: string;
user?: UserProfileBasic;
timestamp?: string;
endpoint?: string;
};

/** -------- User Profile Update/Delete -------- */
export type UpdateUserProfileInput = Partial<Pick<
UserProfile,
"username" | "preferredLanguages" | "preferredCategories" | "favoriteMovies"
>>;

export type UpdateUserProfileResponse = { message: string; data: UserProfile };
export type DeleteUserProfileResponse = { message: string };

/** -------- Ratings & Comments (query returns arrays) -------- */
export type GetUserRatingsResponse = { message: string; ratings: Rating[] };
export type GetUserCommentsResponse = { message: string; comments: Comment[] };

/** -------- Follows -------- */
export type FollowBody = { followingId: string };
export type FollowUnfollowResponse = { message: string };
export type GetFollowersResponse = { followers: FollowEdge[] };
export type GetFollowingResponse = { following: FollowEdge[] };

/** -------- Movies -------- */
// GET /movies/:tmdbId (TMDB fetch + save) and GET/PUT /movies/cinecircle/:movieId
export type GetMovieEnvelope = ApiEnvelope<Movie>;
export type UpdateMovieInput = Partial<Pick<
Movie,
"title" | "description" | "languages" | "imdbRating" | "localRating" | "numRatings"
>>;
export type UpdateMovieEnvelope = ApiEnvelope<Movie>;
export type DeleteMovieResponse = { message: string };
Loading