Skip to content
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

Api fix #118

Merged
merged 23 commits into from
Jul 14, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
11 changes: 8 additions & 3 deletions src/app/(authroutes)/login/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import React from "react";
import { apiCall } from '@/helpers/api';
import toast from "react-hot-toast";

interface Props {
children: React.ReactNode;
}

async function getAuth() {
const res = await fetch("/api/auth");
const json = await res.json();
return json;
try {
const response = await apiCall("/auth");
return response;
} catch (error) {
toast.error("Error Authenticating");
}
}

const LoginModalLayout = ({ children }: Props) => {
Expand Down
4 changes: 2 additions & 2 deletions src/components/NewTableComponent/JobModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import CircularProgress from '@mui/material/CircularProgress';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { grey } from '@mui/material/colors';
import Loader from '@/components/Loader/loader';
import {fetchEachJob} from "@/helpers/api"
const theme = createTheme({
palette: {
primary: {
Expand Down Expand Up @@ -56,8 +57,7 @@ export default function ViewJobModal({ open, setOpen, id }) {
const fetchJobData = async () => {
setLoading(true);
try {
const response = await fetch(`${baseUrl}/api/v1/jobs/${id}`);
const data = await response.json();
const data = await fetchEachJob(id);
JaiPannu-IITI marked this conversation as resolved.
Show resolved Hide resolved
JaiPannu-IITI marked this conversation as resolved.
Show resolved Hide resolved
setJobData(data);
} catch (error) {
console.error('Error fetching job data:', error);
Expand Down
9 changes: 3 additions & 6 deletions src/components/NewTableComponent/PenaltyModal.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState } from 'react';
import { Box, Button, Modal, TextField, Typography } from '@mui/material';

import {apiCall} from "@/helpers/api"
const style = {
position: 'absolute',
top: '50%',
Expand Down Expand Up @@ -29,12 +29,9 @@ const PenaltyModal = ({ isOpen, onClose, studentId }) => {
];

try {
const response = await fetch(`${baseUrl}/api/v1/penalties`, {
const response = await apiCall('/penalties', {
JaiPannu-IITI marked this conversation as resolved.
Show resolved Hide resolved
JaiPannu-IITI marked this conversation as resolved.
Show resolved Hide resolved
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
body: requestBody,
});

if (response.ok) {
Expand Down
6 changes: 3 additions & 3 deletions src/components/NewTableComponent/RecruiterModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import CircularProgress from '@mui/material/CircularProgress';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { grey } from '@mui/material/colors';
import Loader from '@/components/Loader/loader';
import {apiCall} from "@/helpers/api"
const theme = createTheme({
palette: {
primary: {
Expand Down Expand Up @@ -56,9 +57,8 @@ export default function RecruiterModal({ open, setOpen, id }) {
const fetchRecruiterData = async () => {
setLoading(true);
try {
const response = await fetch(`${baseUrl}/api/v1/recruiters/${id}`);
const data = await response.json();
setRecruiterData(data);
const data = await apiCall(`/recruiters/${id}`);
setRecruiterData(data);
} catch (error) {
console.error('Error fetching recruiter data:', error);
}
Expand Down
35 changes: 21 additions & 14 deletions src/components/loginForms/loginWithEmail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,29 @@ import React from "react";
import { url } from "../../helpers/api";
import LockImg from "@/../public/icons/lock.svg";
import toast from "react-hot-toast";

import { apiCall } from "@/helpers/api";
export const LoginWithEmail = (params: { email: String }) => {
const onClick = async () => {
const res = await fetch(url("/auth/passwordless"), {
method: "POST",
cache: "no-store",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({ email: params.email }),
});
console.log(res);
const resOk = res.ok;
if (resOk) toast.success("Email Has Been Sent");
else toast.error("Cannot Login")
return resOk;
try {
const { email } = params;
const response = await apiCall("/auth/passwordless", {
mittal-ishaan marked this conversation as resolved.
Show resolved Hide resolved
method: "POST",
body: { email },
});

if (response.ok) {
toast.success("Email has been sent");
// Optionally handle further actions upon successful response
} else {
toast.error("Cannot login");
}

return response.ok;
} catch (error) {
console.error("Error:", error);
toast.error("An error occurred while sending the email");
return false;
}
};

return (
Expand Down
159 changes: 40 additions & 119 deletions src/helpers/api.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const redirect = () => {};
const baseUrl = process.env.NEXT_PUBLIC_BACKEND_URL;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
import qs from "qs";
import Cookies from "js-cookie";
import { ResumePatchData } from "./types";

const baseUrl = process.env.NEXT_PUBLIC_BACKEND_URL;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

interface ApiCallOptions {
method?: string;
isAuth?: boolean;
Expand All @@ -14,14 +14,13 @@ interface ApiCallOptions {
formData?: FormData;
}

export const url = (NextUrl: string) => {
return `${baseUrl}/api/v1${NextUrl}`;
};
const redirect = () => {

export const getUrl = (NextUrl: string) => {
return `${baseUrl}/api/v1${NextUrl}`;
};

export const url = (NextUrl: string) => { return `${baseUrl}/api/v1${NextUrl}`; };
export const getUrl = (NextUrl: string) => { return `${baseUrl}/api/v1${NextUrl}`;};

export const apiCall = async (
path: string,
{
Expand All @@ -39,7 +38,7 @@ export const apiCall = async (
return;
}

let url = getUrl(path);
let requestUrl = getUrl(path);

const headers: HeadersInit = {};

Expand All @@ -64,7 +63,7 @@ export const apiCall = async (
encodeValuesOnly: true,
encode: false,
});
url += `?${encodedQueryString}`;
requestUrl += `?${encodedQueryString}`;
}

if (isAuth) {
Expand All @@ -77,22 +76,25 @@ export const apiCall = async (
req["next"] = next;
}

const res = await fetch(url, req);
const res = await fetch(requestUrl, req);

if (method === "GET") {
return await res.json();
} else return res.ok;
} else{
return res.ok
};
};
export const OpenFile = async (
path: string,
{ method = "GET", isAuth = true, next = null }: ApiCallOptions = {}
) => {

export const OpenFile = async (path: string, options: ApiCallOptions = {}) => {
const { method = "GET", isAuth = true, next = null } = options;

const accessToken = Cookies.get("accessToken");
if ((!accessToken || accessToken === undefined) && isAuth) {
redirect();
return;
}

let url = getUrl(path);
let requestUrl = getUrl(path);

const headers: HeadersInit = {};

Expand All @@ -110,11 +112,11 @@ export const OpenFile = async (
req["next"] = next;
}

fetch(url, req)
fetch(requestUrl, req)
.then((response) => response.blob())
.then((blob) => {
const url = window.URL.createObjectURL(blob);
window.open(url);
const fileUrl = window.URL.createObjectURL(blob);
window.open(fileUrl);
})
.catch((error) => console.error("Error:", error));
};
Expand All @@ -136,71 +138,31 @@ export const PasswordlessLogin = async (accessToken: string | undefined) => {
};

export const fetchAllSeasons = async (accessToken: string | undefined) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(url("/seasons"), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const json = await res.json();
return json;
return apiCall("/seasons");
};

export const fetchCompany = async (accessToken: string | undefined) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(url("/companies"), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const json = await res.json();
return json;
return apiCall("/companies");
};

export const fetchAllJobs = async (
accessToken: string | undefined,
filter: string | undefined
) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(filter ? url(`/jobs?${filter}`) : url("/jobs"), {
return apiCall(filter ? `/jobs?${filter}` : "/jobs", {

next: { tags: ["AllJobs"] },
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const json = await res.json();
return json;
// return SampleJobData
};

export const fetchStudentData = async (
accessToken: string | undefined,
filter: string | undefined
) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(
filter ? url(`/students?${filter}`) : url("/students"),
{
next: { tags: ["AllStudents"] },
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const json = await res.json();
return json;
return apiCall(filter ? `/students?${filter}` : "/students", {

next: { tags: ["AllStudents"] },
});
};

export const fetchSeasonData = async (
Expand Down Expand Up @@ -228,57 +190,27 @@ export const fetchCompanyRecruiters = async (
accessToken: string | undefined,
companyId: string | undefined
) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(`${url("/companies")}/${companyId}/recruiters/`, {
next: {
tags: ["AllRecruiters"],
},
headers: {
Authorization: `Bearer ${accessToken}`,
},
return apiCall(`/companies/${companyId}/recruiters/`, {

next: { tags: ["AllRecruiters"] },
});
const json = await res.json();
return json;
};

export const fetchJobSalary = async (
accessToken: string | undefined,
jobId: string | undefined
) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(`${url("/jobs")}/${jobId}/salary/`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const json = await res.json();
return json;
return apiCall(`/jobs/${jobId}/salary/`);
};

export const fetchEachJob = async (
accessToken: string | undefined,
jobId: any
mittal-ishaan marked this conversation as resolved.
Show resolved Hide resolved
) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}
const res = await fetch(`${url("/jobs")}/${jobId}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

const json = await res.json();
return json;
return apiCall(`/jobs/${jobId}`);
};


export const fetchJobEvents = async (jobId: any) => {
return apiCall(`/events`, {
queryParam: {
Expand Down Expand Up @@ -317,22 +249,11 @@ export const fetchRecruiterData = async (
accessToken: string | undefined,
filter: string | undefined
) => {
if (!accessToken || accessToken === undefined) {
redirect();
return;
}

const res = await fetch(
filter ? url(`/recruiters?${filter}`) : url("/recruiters"),
{
next: { tags: ["AllRecruiters"] },
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const json = await res.json();
return json;
return apiCall(filter ? `/recruiters?${filter}` : "/recruiters", {
next: { tags: ["AllRecruiters"] },
});

};

export const fetchResumes = async () => {
Expand Down
Loading