Skip to content

Commit 4db859f

Browse files
authored
Refactor API utility functions and update commons-ui dependency to 0.132.0 (#143)
Signed-off-by: achour94 <[email protected]>
1 parent 2be3695 commit 4db859f

File tree

6 files changed

+14
-72
lines changed

6 files changed

+14
-72
lines changed

package-lock.json

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"dependencies": {
1717
"@emotion/react": "^11.14.0",
1818
"@emotion/styled": "^11.14.1",
19-
"@gridsuite/commons-ui": "0.130.0",
19+
"@gridsuite/commons-ui": "0.132.0",
2020
"@hookform/resolvers": "^4.1.3",
2121
"@mui/icons-material": "^5.18.0",
2222
"@mui/lab": "5.0.0-alpha.175",

src/services/directory.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
66
*/
77

8-
import { backendFetchJson, getRestBase } from '../utils/api-rest';
8+
import { getRestBase } from '../utils/api-rest';
99
import type { UUID } from 'node:crypto';
10-
import { ElementAttributes } from '@gridsuite/commons-ui';
10+
import { ElementAttributes, backendFetchJson } from '@gridsuite/commons-ui';
1111

1212
const EXPLORE_URL = `${getRestBase()}/explore/v1`;
1313

src/services/study.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
66
*/
77

8-
import { GridSuiteModule } from '@gridsuite/commons-ui';
9-
import { backendFetchJson, getRestBase } from '../utils/api-rest';
8+
import { GridSuiteModule, backendFetchJson } from '@gridsuite/commons-ui';
9+
import { getRestBase } from '../utils/api-rest';
1010
import { getErrorMessage } from '../utils/error';
1111
import { APP_NAME } from '../utils/config-params';
1212

src/services/user-admin.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
66
*/
77

8-
import { backendFetch, backendFetchJson, getRestBase } from '../utils/api-rest';
8+
import { backendFetch, backendFetchJson } from '@gridsuite/commons-ui';
9+
import { getRestBase } from '../utils/api-rest';
910
import type { UUID } from 'node:crypto';
1011

1112
const USER_ADMIN_URL = `${getRestBase()}/user-admin/v1`;
@@ -23,7 +24,7 @@ export type UserInfos = UserInfosUpdate & {
2324

2425
export function fetchUsers(): Promise<UserInfos[]> {
2526
console.debug(`Fetching list of users...`);
26-
return backendFetchJson<UserInfos[]>(`${USER_ADMIN_URL}/users`, {
27+
return backendFetchJson(`${USER_ADMIN_URL}/users`, {
2728
headers: {
2829
Accept: 'application/json',
2930
//'Content-Type': 'application/json; utf-8',
@@ -271,7 +272,7 @@ export type Announcement = NewAnnouncement & {
271272

272273
export async function addAnnouncement(announcement: NewAnnouncement) {
273274
console.debug(`Creating announcement ...`);
274-
return backendFetchJson<Announcement>(
275+
return backendFetchJson(
275276
`${USER_ADMIN_URL}/announcements?startDate=${announcement.startDate}&endDate=${announcement.endDate}&severity=${announcement.severity}`,
276277
{
277278
method: 'put',
@@ -290,7 +291,7 @@ export async function addAnnouncement(announcement: NewAnnouncement) {
290291
export async function fetchAnnouncementList() {
291292
console.debug(`Fetching announcement ...`);
292293
try {
293-
return await backendFetchJson<Announcement[]>(`${USER_ADMIN_URL}/announcements`, { method: 'get' });
294+
return await backendFetchJson(`${USER_ADMIN_URL}/announcements`, { method: 'get' });
294295
} catch (reason) {
295296
console.error('Error while fetching announcement:', reason);
296297
throw reason;

src/utils/api-rest.ts

Lines changed: 0 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -5,66 +5,7 @@
55
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
66
*/
77

8-
import type { JsonValue } from 'type-fest';
9-
import { getToken, parseError, Token } from './api';
10-
11-
export type { Token } from './api';
12-
13-
export interface ErrorWithStatus extends Error {
14-
status?: number;
15-
}
16-
17-
export type Url = string | URL;
18-
export type InitRequest = Partial<RequestInit>;
19-
208
export function getRestBase(): string {
219
// We use the `baseURI` (from `<base/>` in index.html) to build the URL, which is corrected by httpd/nginx
2210
return document.baseURI.replace(/\/+$/, '') + import.meta.env.VITE_API_GATEWAY;
2311
}
24-
25-
function handleError(response: Response): Promise<never> {
26-
return response.text().then((text: string) => {
27-
const errorName = 'HttpResponseError : ';
28-
let error: ErrorWithStatus;
29-
const errorJson = parseError(text);
30-
if (errorJson?.status && errorJson?.error && errorJson?.message) {
31-
error = new Error(
32-
`${errorName}${errorJson.status} ${errorJson.error}, message : ${errorJson.message}`
33-
) as ErrorWithStatus;
34-
error.status = errorJson.status;
35-
} else {
36-
error = new Error(
37-
`${errorName}${response.status} ${response.statusText}, message : ${text}`
38-
) as ErrorWithStatus;
39-
error.status = response.status;
40-
}
41-
throw error;
42-
});
43-
}
44-
45-
function prepareRequest(init?: InitRequest, token?: Token): RequestInit {
46-
if (!(typeof init === 'undefined' || typeof init === 'object')) {
47-
throw new TypeError(`Argument 2 of backendFetch is not an object ${typeof init}`);
48-
}
49-
const initCopy: RequestInit = { ...init };
50-
initCopy.headers = new Headers(initCopy.headers || {});
51-
const tokenCopy = token || getToken();
52-
initCopy.headers.append('Authorization', `Bearer ${tokenCopy}`);
53-
return initCopy;
54-
}
55-
56-
function safeFetch(url: Url, initCopy?: InitRequest) {
57-
return fetch(url, initCopy).then((response: Response) => (response.ok ? response : handleError(response)));
58-
}
59-
60-
export function backendFetch(url: Url, init?: InitRequest, token?: Token): Promise<Response> {
61-
return safeFetch(url, prepareRequest(init, token));
62-
}
63-
64-
export function backendFetchText<R extends string = string>(url: Url, init?: InitRequest, token?: Token) {
65-
return backendFetch(url, init, token).then((safeResponse) => safeResponse.text()) as Promise<R>;
66-
}
67-
68-
export function backendFetchJson<R extends JsonValue>(url: Url, init?: InitRequest, token?: Token): Promise<R> {
69-
return backendFetch(url, init, token).then((safeResponse) => safeResponse.json());
70-
}

0 commit comments

Comments
 (0)