Skip to content

Commit

Permalink
Merge pull request #29 from MuNuChapterHKN/refactor/api-ts
Browse files Browse the repository at this point in the history
Refactor frontend API calls
  • Loading branch information
AlbertoBaroso authored Jun 27, 2024
2 parents 1da23b8 + a7d2ba7 commit e8a5faa
Show file tree
Hide file tree
Showing 10 changed files with 194 additions and 40 deletions.
139 changes: 102 additions & 37 deletions frontend/src/services/API.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,109 @@
async function apiRequest(endpoint: string, how: string, params?: any) {
debugger;
const body = how === "GET" ? undefined : JSON.stringify(params);
const response = await fetch(endpoint, { method: how, body: body });
const data = await response.json();
return data;
}
import users from "./users";
import applications from "./applications";
import timeSlots from "./timeSlots";
import interviews from "./interviews";
import availabilities from "./availabilities";
import recruitmentSessions from "./recruitmentSessions";

export async function getApplicants() {
return await apiRequest("/v1/applications", "GET");
}
const api = {
users,
applications,
timeSlots,
interviews,
availabilities,
recruitmentSessions,
};

export async function getUsers() {
return await apiRequest("/v1/users", "GET");
}
export default api;

// Supposizioni
type HttpRequestOptions = {
authToken?: string;
body?: object;
};

export async function getInterviewsByDates(startDate: string, endDate: string) {
return await apiRequest(
`/v1/interviews?startDate=${startDate}&endDate=${endDate}}`,
"GET"
);
}
export class Api {
private static getUrl = (endpoint: string) =>
`${process.env.REACT_APP_API_ENDPOINT}/v1/${endpoint}`;

export async function getInterviewsByDate(date: string) {
return await apiRequest(`/v1/interviews?date=${date}`, "GET");
}
static async httpRequest(
endpoint: string,
method: string,
options: HttpRequestOptions = {}
) {
let response;

/*
const GetApplicants = ({ name }) => {
const [count, setCount] = React.useState(0);
return (
<div>
<h1>Hello, {name}!</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
try {
/* Prepare request parameters */
const headers: HeadersInit = await Api.buildHeaders(
options.authToken ?? "",
true
);
const init = {
method,
headers,
};
if (options.body) init["body"] = JSON.stringify(options.body);
/* Send the request */
response = await fetch(new URL(this.getUrl(endpoint)), init);
} catch (error) {
console.log(error);
throw new Error("Something went wrong, try again later.");
}

return await this.handleResponse(response);
}

export default GetApplicants;
*/
static async get(endpoint: string, authToken: string = "") {
return Api.httpRequest(endpoint, "GET", { authToken });
}

static async post(
endpoint: string,
body: object = {},
authToken: string = ""
) {
return Api.httpRequest(endpoint, "POST", { authToken, body });
}

static async put(
endpoint: string,
body: object = {},
authToken: string = ""
) {
return Api.httpRequest(endpoint, "PUT", { authToken, body });
}

static async patch(
endpoint: string,
body: object = {},
authToken: string = ""
) {
return Api.httpRequest(endpoint, "PATCH", { authToken, body });
}

static async delete(endpoint: string, authToken: string = "") {
return Api.httpRequest(endpoint, "DELETE", { authToken });
}

static async handleResponse(response: Response) {
console.log(">>>", response);

if (!response.ok) throw new Error(response.statusText);

return await response.json();
}

static async buildHeaders(
token: string = "",
json: boolean = false
): Promise<HeadersInit> {
const headers: HeadersInit = new Headers();
if (token) {
headers.append("Authorization", `Bearer ${token}`);
}
if (json) {
headers.append("Content-Type", "application/json");
}
return headers;
}
}
11 changes: 11 additions & 0 deletions frontend/src/services/applications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Api } from "./api";

const resource = "applications";

const applications = {
getApplications: async (accessToken: string | undefined) => {
return await Api.get(`${resource}`, accessToken);
},
};

export default applications;
11 changes: 11 additions & 0 deletions frontend/src/services/availabilities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Api } from "./api";

const resource = "availabilities";

const availabilities = {
getAvailabilities: async (accessToken: string | undefined) => {
return await Api.get(`${resource}`, accessToken);
},
};

export default availabilities;
3 changes: 3 additions & 0 deletions frontend/src/services/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import api from "./api";

export { api };
24 changes: 24 additions & 0 deletions frontend/src/services/interviews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Api } from "./api";

const resource = "interviews";

const interviews = {
getInterviewsByDates: async (
startDate: string,
endDate: string,
accessToken: string | undefined
) => {
return await Api.get(
`${resource}?startDate=${startDate}&endDate=${endDate}}`,
accessToken
);
},
getInterviewsByDate: async (
date: string,
accessToken: string | undefined
) => {
return await Api.get(`${resource}?date=${date}`, accessToken);
},
};

export default interviews;
11 changes: 11 additions & 0 deletions frontend/src/services/recruitmentSessions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Api } from "./api";

const resource = "recruitment-session";

const recruitmentSessions = {
getActive: async (accessToken: string | undefined) => {
return await Api.get(`${resource}`, accessToken);
},
};

export default recruitmentSessions;
11 changes: 11 additions & 0 deletions frontend/src/services/timeslots.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Api } from "./api";

const resource = "timeslots";

const timeslots = {
getApplicants: async (accessToken: string | undefined) => {
return await Api.get(`${resource}`, accessToken);
},
};

export default timeslots;
11 changes: 11 additions & 0 deletions frontend/src/services/users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Api } from "./api";

const resource = "users";

const users = {
getUsers: async (accessToken: string | undefined) => {
return await Api.get(`${resource}`, accessToken);
},
};

export default users;
7 changes: 6 additions & 1 deletion frontend/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { defineConfig } from "vite";
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";

const env = loadEnv(process.env.NODE_ENV ?? 'development', process.cwd(), '');

// https://vitejs.dev/config/
export default defineConfig({
define: {
'process.env.REACT_APP_API_ENDPOINT': JSON.stringify(env.REACT_APP_API_ENDPOINT)
},
plugins: [react()],
});
6 changes: 4 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit e8a5faa

Please sign in to comment.