-
Notifications
You must be signed in to change notification settings - Fork 0
[WIP] FE API Service #35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 6f7a536
Merge branch 'main' of https://github.com/GenerateNU/cinecircle into …
tGiech22 d9a8814
chore: saving changes
tGiech22 1b14c1e
Chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 5550b4a
Ratings type
abby-stevenson 8491ab1
Adding Rating to schema
abby-stevenson 9b10360
Adding the create new rating
abby-stevenson fdd2d98
update to ratings
abby-stevenson 98fe676
middleware
abby-stevenson 6bd44c8
Deleting fake middleware
abby-stevenson af569d4
Adding tests
abby-stevenson 676f665
Adding votes and removing double rating
abby-stevenson ef59c56
Rest of Crud
abby-stevenson 8084d31
Fix: Add /api prefix in routes/index.ts
danctila 62eb249
Fix: Check for Authorization header in auth mocks
danctila 2eaa444
Fix: remove threadedComments from rating creation
danctila 00fb691
fix: adding mapping functions
tGiech22 d0928ed
Merge branch 'main' of https://github.com/GenerateNU/cinecircle into …
tGiech22 45a944c
Merge branch 'main' of https://github.com/GenerateNU/cinecircle into …
tGiech22 00de2f8
saving changes
tGiech22 9f2b25e
chore: resolving merge conflicts
tGiech22 836b984
chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 6f2aefb
fix: adding mapping functions to tmdb.ts
tGiech22 a12d486
fix: this schema.prisma file seems to work
tGiech22 34fb614
chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 0a4aef3
fix: adding mapping functions for user.ts
tGiech22 aba6618
saving changes
tGiech22 0cf77f5
refactor: redoing mapping functions
tGiech22 8907c3e
fix: deleting unnecessary model
tGiech22 6ac0f03
fix: added mapping function for movies and tests
tGiech22 c5eca2a
fix: fixing import paths
tGiech22 dac6546
fix: adding mapping functions for user.ts and userFollows.ts
tGiech22 b70d20c
fix: changing imdbRating to BigInt for a test in movie.api.tests
tGiech22 6920c66
chore: Merge branch 'main' of https://github.com/GenerateNU/cinecircl…
tGiech22 e049fdb
fix: removing unnecessary mapper and tests for movie
tGiech22 e9e40e2
fix: fixing import for movie unit tests
tGiech22 4437b2a
fix: fixing mapping function usage
tGiech22 aa943b9
adding tests for userFollows
tGiech22 85e4c86
fix: fixing mapping function of tmdb
tGiech22 208c613
fix: fixing movie unit tests
tGiech22 82ee106
fix: fixing tests
tGiech22 2667012
fix: user schema relation names
danctila ae42136
fix: rm doc directory
danctila f76f3e4
Merge branch 'main' into frontend-api-service
danctila e8e9981
remove chat comments
danctila File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 || | ||
| "http://localhost:3000"; | ||
|
|
||
| export const api = new ApiClient({ | ||
| baseUrl: BASE_URL, | ||
| getToken: () => | ||
| typeof window !== "undefined" ? localStorage.getItem("token") || undefined : undefined, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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`); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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`); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}`); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.