Skip to content

Commit 5a58db5

Browse files
authored
Merge pull request #1421 from fabiovincenzi/fix/async-await-consistency
refactor: replace async/await and promise chaining
2 parents 1bda10c + 8606a21 commit 5a58db5

3 files changed

Lines changed: 72 additions & 71 deletions

File tree

src/ui/services/config.ts

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,35 +6,31 @@ import { getApiV1BaseUrl } from './apiConfig';
66
const setAttestationConfigData = async (setData: (data: QuestionFormData[]) => void) => {
77
const apiV1Base = await getApiV1BaseUrl();
88
const url = new URL(`${apiV1Base}/config/attestation`);
9-
await axios(url.toString()).then((response) => {
10-
setData(response.data.questions);
11-
});
9+
const response = await axios(url.toString());
10+
setData(response.data.questions);
1211
};
1312

1413
const setURLShortenerData = async (setData: (data: string) => void) => {
1514
const apiV1Base = await getApiV1BaseUrl();
1615
const url = new URL(`${apiV1Base}/config/urlShortener`);
17-
await axios(url.toString()).then((response) => {
18-
setData(response.data);
19-
});
16+
const response = await axios(url.toString());
17+
setData(response.data);
2018
};
2119

2220
const setEmailContactData = async (setData: (data: string) => void) => {
2321
const apiV1Base = await getApiV1BaseUrl();
2422
const url = new URL(`${apiV1Base}/config/contactEmail`);
25-
await axios(url.toString()).then((response) => {
26-
setData(response.data);
27-
});
23+
const response = await axios(url.toString());
24+
setData(response.data);
2825
};
2926

3027
const setUIRouteAuthData = async (setData: (data: UIRouteAuth) => void) => {
3128
const apiV1Base = await getApiV1BaseUrl();
3229
const urlString = `${apiV1Base}/config/uiRouteAuth`;
3330
console.log(`URL: ${urlString}`);
3431
const url = new URL(urlString);
35-
await axios(url.toString()).then((response) => {
36-
setData(response.data);
37-
});
32+
const response = await axios(url.toString());
33+
setData(response.data);
3834
};
3935

4036
export { setAttestationConfigData, setURLShortenerData, setEmailContactData, setUIRouteAuthData };

src/ui/services/repo.ts

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,18 @@ import { ServiceResult, getServiceError, errorResult, successResult } from './er
88
const canAddUser = async (repoId: string, user: string, action: string) => {
99
const apiV1Base = await getApiV1BaseUrl();
1010
const url = new URL(`${apiV1Base}/repo/${repoId}`);
11-
return axios
12-
.get<Repo>(url.toString(), getAxiosConfig())
13-
.then((response) => {
14-
const repo = response.data;
15-
if (action === 'authorise') {
16-
return !repo.users.canAuthorise.includes(user);
17-
} else {
18-
return !repo.users.canPush.includes(user);
19-
}
20-
})
21-
.catch((error: any) => {
22-
const { message } = getServiceError(error, 'Failed to validate repo permissions');
23-
throw new Error(message);
24-
});
11+
try {
12+
const response = await axios.get<Repo>(url.toString(), getAxiosConfig());
13+
const repo = response.data;
14+
if (action === 'authorise') {
15+
return !repo.users.canAuthorise.includes(user);
16+
} else {
17+
return !repo.users.canPush.includes(user);
18+
}
19+
} catch (error: any) {
20+
const { message } = getServiceError(error, 'Failed to validate repo permissions');
21+
throw new Error(message);
22+
}
2523
};
2624

2725
class DupUserValidationError extends Error {
@@ -79,11 +77,13 @@ const addUser = async (repoId: string, user: string, action: string): Promise<vo
7977
const apiV1Base = await getApiV1BaseUrl();
8078
const url = new URL(`${apiV1Base}/repo/${repoId}/user/${action}`);
8179
const data = { username: user };
82-
await axios.patch(url.toString(), data, getAxiosConfig()).catch((error: any) => {
80+
try {
81+
await axios.patch(url.toString(), data, getAxiosConfig());
82+
} catch (error: any) {
8383
const { message } = getServiceError(error, 'Failed to add user');
8484
console.log(message);
8585
throw new Error(message);
86-
});
86+
}
8787
} else {
8888
console.log('Duplicate user can not be added');
8989
throw new DupUserValidationError('Duplicate user can not be added');
@@ -94,22 +94,26 @@ const deleteUser = async (user: string, repoId: string, action: string): Promise
9494
const apiV1Base = await getApiV1BaseUrl();
9595
const url = new URL(`${apiV1Base}/repo/${repoId}/user/${action}/${user}`);
9696

97-
await axios.delete(url.toString(), getAxiosConfig()).catch((error: any) => {
97+
try {
98+
await axios.delete(url.toString(), getAxiosConfig());
99+
} catch (error: any) {
98100
const { message } = getServiceError(error, 'Failed to remove user');
99101
console.log(message);
100102
throw new Error(message);
101-
});
103+
}
102104
};
103105

104106
const deleteRepo = async (repoId: string): Promise<void> => {
105107
const apiV1Base = await getApiV1BaseUrl();
106108
const url = new URL(`${apiV1Base}/repo/${repoId}/delete`);
107109

108-
await axios.delete(url.toString(), getAxiosConfig()).catch((error: any) => {
110+
try {
111+
await axios.delete(url.toString(), getAxiosConfig());
112+
} catch (error: any) {
109113
const { message } = getServiceError(error, 'Failed to delete repository');
110114
console.log(message);
111115
throw new Error(message);
112-
});
116+
}
113117
};
114118

115119
export { addUser, deleteUser, getRepos, getRepo, addRepo, deleteRepo };

src/ui/views/Login/Login.tsx

Lines changed: 40 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,21 @@ const Login: React.FC = () => {
3636
const [usernamePasswordMethod, setUsernamePasswordMethod] = useState<string>('');
3737

3838
useEffect(() => {
39-
getBaseUrl().then((baseUrl) => {
40-
axios.get(`${baseUrl}/api/auth/config`).then((response) => {
41-
const usernamePasswordMethod = response.data.usernamePasswordMethod;
42-
const otherMethods = response.data.otherMethods;
39+
const fetchAuthConfig = async () => {
40+
const baseUrl = await getBaseUrl();
41+
const response = await axios.get(`${baseUrl}/api/auth/config`);
42+
const usernamePasswordMethod = response.data.usernamePasswordMethod;
43+
const otherMethods = response.data.otherMethods;
4344

44-
setUsernamePasswordMethod(usernamePasswordMethod);
45-
setAuthMethods(otherMethods);
45+
setUsernamePasswordMethod(usernamePasswordMethod);
46+
setAuthMethods(otherMethods);
4647

47-
// Automatically login if only one non-username/password method is enabled
48-
if (!usernamePasswordMethod && otherMethods.length === 1) {
49-
handleAuthMethodLogin(otherMethods[0]);
50-
}
51-
});
52-
});
48+
// Automatically login if only one non-username/password method is enabled
49+
if (!usernamePasswordMethod && otherMethods.length === 1) {
50+
await handleAuthMethodLogin(otherMethods[0]);
51+
}
52+
};
53+
fetchAuthConfig();
5354
}, []);
5455

5556
function validateForm(): boolean {
@@ -58,40 +59,40 @@ const Login: React.FC = () => {
5859
);
5960
}
6061

61-
function handleAuthMethodLogin(authMethod: string): void {
62-
getBaseUrl().then((baseUrl) => {
63-
window.location.href = `${baseUrl}/api/auth/${authMethod}`;
64-
});
62+
async function handleAuthMethodLogin(authMethod: string): Promise<void> {
63+
const baseUrl = await getBaseUrl();
64+
window.location.href = `${baseUrl}/api/auth/${authMethod}`;
6565
}
6666

67-
function handleSubmit(event: FormEvent): void {
67+
async function handleSubmit(event: FormEvent): Promise<void> {
6868
event.preventDefault();
6969
setIsLoading(true);
7070

71-
getBaseUrl().then((baseUrl) => {
71+
try {
72+
const baseUrl = await getBaseUrl();
7273
const loginUrl = `${baseUrl}/api/auth/login`;
73-
axios
74-
.post<LoginResponse>(loginUrl, { username, password }, getAxiosConfig())
75-
.then(() => {
74+
await axios.post<LoginResponse>(loginUrl, { username, password }, getAxiosConfig());
75+
window.sessionStorage.setItem('git.proxy.login', 'success');
76+
setMessage('Success!');
77+
setSuccess(true);
78+
await authContext.refreshUser();
79+
navigate(0);
80+
} catch (error: unknown) {
81+
if (error instanceof AxiosError) {
82+
if (error.response?.status === 307) {
7683
window.sessionStorage.setItem('git.proxy.login', 'success');
77-
setMessage('Success!');
78-
setSuccess(true);
79-
authContext.refreshUser().then(() => navigate(0));
80-
})
81-
.catch((error: AxiosError) => {
82-
if (error.response?.status === 307) {
83-
window.sessionStorage.setItem('git.proxy.login', 'success');
84-
setGitAccountError(true);
85-
} else if (error.response?.status === 403) {
86-
setMessage(processAuthError(error, false));
87-
} else {
88-
setMessage('You entered an invalid username or password...');
89-
}
90-
})
91-
.finally(() => {
92-
setIsLoading(false);
93-
});
94-
});
84+
setGitAccountError(true);
85+
} else if (error.response?.status === 403) {
86+
setMessage(processAuthError(error, false));
87+
} else {
88+
setMessage('You entered an invalid username or password...');
89+
}
90+
} else {
91+
setMessage('You entered an invalid username or password...');
92+
}
93+
} finally {
94+
setIsLoading(false);
95+
}
9596
}
9697

9798
if (gitAccountError) {

0 commit comments

Comments
 (0)