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

refactor(app): New API service #4381

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
37 changes: 16 additions & 21 deletions app/src/app.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
import { setYoung } from "./redux/auth/actions";
import { startReactDsfr } from "@codegouvfr/react-dsfr/spa";
import { maintenance } from "./config";
import api, { initApi } from "./services/api";
import api from "./services/api.service";
import { queryClient } from "./services/react-query";
import { shouldForceRedirectToEmailValidation } from "./utils/navigation";
import { cohortsInit } from "./utils/cohorts";
Expand All @@ -38,25 +38,23 @@ const RepresentantsLegaux = lazy(() => import("./scenes/representants-legaux"));
const Thanks = lazy(() => import("./scenes/contact/Thanks"));
const ViewMessage = lazy(() => import("./scenes/echanges/View"));

initApi();
startReactDsfr({ defaultColorScheme: "light", Link });

function App() {
const [loading, setLoading] = useState(true);
const dispatch = useDispatch();
const young = useSelector((state) => state.Auth.young);
const { pathname, hash } = useLocation();

async function fetchData() {
try {
const { ok, user, token } = await api.checkToken();
const { ok, user } = await api.getUser();

if (!ok || !user || !token) {
api.setToken(null);
if (!ok || !user) {
dispatch(setYoung(null));
return;
}

api.setToken(token);
dispatch(setYoung(user));
await cohortsInit();

Expand All @@ -74,6 +72,10 @@ function App() {
fetchData();
}, []);

useEffect(() => {
handleScroll(pathname, hash);
}, [pathname, hash]);

if (loading) return <PageLoader />;

if (maintenance) return <Maintenance />;
Expand All @@ -82,7 +84,6 @@ function App() {
<Sentry.ErrorBoundary fallback={FallbackComponent}>
<QueryClientProvider client={queryClient}>
<Router history={history}>
<AutoScroll />
<Suspense fallback={<PageLoader />}>
<Switch>
<Redirect from={"/public-besoin-d-aide"} to={"/besoin-d-aide"} />
Expand Down Expand Up @@ -126,19 +127,13 @@ function SecureRoute({ path, component }) {
return <SentryRoute path={path} component={component} />;
}

function AutoScroll() {
const { pathname, hash } = useLocation();

useEffect(() => {
if (hash) {
const element = document.getElementById(hash.replace("#", ""));
if (element) {
element.scrollIntoView({ behavior: "smooth" });
return;
}
function handleScroll(pathname, hash) {
if (hash) {
const element = document.getElementById(hash.replace("#", ""));
if (element) {
element.scrollIntoView({ behavior: "smooth" });
return;
}
window.scrollTo(0, 0);
}, [pathname, hash]);

return null;
}
window.scrollTo(0, 0);
}
122 changes: 122 additions & 0 deletions app/src/services/api.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { apiURL } from "../config";
import { createFormDataForFileUpload, ERRORS, YoungDto } from "snu-lib";
import { capture } from "../sentry";

interface Headers {
"x-user-timezone": string;
"Content-Type"?: string;
}

interface Options {
mode: RequestMode;
credentials: RequestCredentials;
}

interface ApiResponse {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utiliser RouteResponseBody depuis la snu-lib

export type RouteResponseBody<T> = { ok: boolean; data?: T; code?: string; message?: string };

ok: boolean;
data?: unknown;
code?: string;
}

interface Api {
get: (path: string) => Promise<ApiResponse>;
post: (path: string, body: unknown) => Promise<ApiResponse>;
put: (path: string, body: unknown) => Promise<ApiResponse>;
remove: (path: string) => Promise<ApiResponse>;
getUser: () => Promise<YoungDto>;
openpdf: (path: string, body: unknown) => Promise<Blob>;
uploadFiles: (path: string, arr: unknown[]) => Promise<ApiResponse>;
}

class api {
headers: Headers;
options: Options;

constructor() {
this.headers = {
"x-user-timezone": new Date().getTimezoneOffset().toString(),
};
this.options = {
mode: "cors",
credentials: "include",
};
}

async get(path: string): Promise<ApiResponse> {
const response = await fetch(`${apiURL}${path}`, {
...this.options,
headers: new Headers({ "Content-Type": "application/json", ...this.headers }),
});
if ([401, 403, 404].includes(response.status)) {
throw new Error(response.status.toString());
}
const res = await response.json();
return res;
}
async post(path: string, body: unknown): Promise<ApiResponse> {
const response = await fetch(`${apiURL}${path}`, {
...this.options,
method: "POST",
headers: { "Content-Type": "application/json", ...this.headers },
body: typeof body === "string" ? body : JSON.stringify(body),
});
if ([401, 403, 404].includes(response.status)) {
throw new Error(response.status.toString());
}
const res = await response.json();
return res;
}
async put(path: string, body: unknown): Promise<ApiResponse> {
const response = await fetch(`${apiURL}${path}`, {
...this.options,
method: "PUT",
headers: { "Content-Type": "application/json", ...this.headers },
body: typeof body === "string" ? body : JSON.stringify(body),
});
if ([401, 403, 404].includes(response.status)) {
throw new Error(response.status.toString());
}
const res = await response.json();
return res;
}
async remove(path: string): Promise<ApiResponse> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pourquoi remove alors qu'on utilise le verbe http DELETE ?

const response = await fetch(`${apiURL}${path}`, {
...this.options,
method: "DELETE",
headers: new Headers({ "Content-Type": "application/json", ...this.headers }),
});
if ([401, 403, 404].includes(response.status)) {
throw new Error(response.status.toString());
}
const res = await response.json();
return res;
}

async getUser() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

du coup si c'est une api générique, il ne faudrait pas avoir de service user dedans non ?

const { data: user } = await this.get(`${apiURL}/young/signin_token`);
return user as YoungDto;
}

async openpdf(path: string, body: unknown) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

downloadPdf plutot non ?

const response = await fetch(`${apiURL}${path}`, {
...this.options,
method: "POST",
headers: new Headers({ "Content-Type": "application/json", ...this.headers }),
body: typeof body === "string" ? body : JSON.stringify(body),
});
if ([401, 403, 404].includes(response.status)) {
throw new Error(response.status.toString());
}
const file = await response.blob();
return file;
}

async uploadFiles(path: string, arr: unknown[]): Promise<ApiResponse> {
const formData = createFormDataForFileUpload(arr);
const res = await this.post(path, formData);
return res;
}
}

const API = new api();
export default API;
2 changes: 1 addition & 1 deletion packages/lib/src/utils/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function download(file, fileName) {
* @param [File]
* @returns FormData
**/
function createFormDataForFileUpload(arr: any[], properties) {
function createFormDataForFileUpload(arr: any[], properties = {}) {
let files: any[] = [];
if (Array.isArray(arr)) files = arr.filter((e) => typeof e === "object");
else files = [arr];
Expand Down
Loading