Skip to content

Commit

Permalink
moved error handling to middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
BatuevIO committed Sep 14, 2024
1 parent 9b9326a commit eeba2b7
Show file tree
Hide file tree
Showing 24 changed files with 103 additions and 144 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@profcomff/api-uilib": "2024.7.28",
"axios": "^1.7.5",
"markdown-it": "^14.1.0",
"openapi-fetch": "^0.12.0",
"pinia": "^2.2.2",
"query-string": "^9.1.0",
"ua-parser-js": "^1.0.38",
Expand Down
15 changes: 15 additions & 0 deletions pnpm-lock.yaml

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

29 changes: 7 additions & 22 deletions src/api/controllers/TimetableApi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { stringifyDate, getDateWithDayOffset } from './../../utils/date';
import { useTimetableStore } from './../../store/timetable';
import apiClient from '@/api/';
import { recordError } from '@/utils/errorHandler';

interface GetLecturersParams {
query?: string;
Expand Down Expand Up @@ -36,73 +35,61 @@ function getLecturers(params?: GetLecturersParams) {
export class TimetableApi {
public static async getLecturer(id: number) {
const { setLecturers } = useTimetableStore();
const { data, error } = await getLecturer(id);
const { data } = await getLecturer(id);
if (data) {
setLecturers([data]);
} else {
recordError(error);
}
}

public static async getLecturers() {
const { setLecturers } = useTimetableStore();
const { data, error } = await getLecturers();
const { data } = await getLecturers();
if (data) {
setLecturers(data.items);
} else {
recordError(error);
}
}

public static async getRoom(id: number) {
const { setRooms } = useTimetableStore();
const { data, error } = await apiClient.GET('/timetable/room/{id}', {
const { data } = await apiClient.GET('/timetable/room/{id}', {
params: { path: { id } },
});
if (data) {
setRooms([data]);
} else {
recordError(error);
}
}

public static async getRooms() {
const { setRooms } = useTimetableStore();
const { data, error } = await apiClient.GET('/timetable/room/');
const { data } = await apiClient.GET('/timetable/room/');
if (data) {
setRooms(data.items);
} else {
recordError(error);
}
}

public static async getEvent(id: number) {
const { setEvents } = useTimetableStore();
const { data, error } = await apiClient.GET('/timetable/event/{id}', {
const { data } = await apiClient.GET('/timetable/event/{id}', {
params: { path: { id } },
});
if (data) {
setEvents([data]);
} else {
recordError(error);
}
}

public static async getEvents(params?: GetEventsParams) {
const { setEvents } = useTimetableStore();
const { data, error } = await apiClient.GET('/timetable/event/', {
const { data } = await apiClient.GET('/timetable/event/', {
params: { query: params },
});
if (data && data !== null) {
setEvents(data.items);
} else {
recordError(error);
}
}

public static async getDayEvents(date: Date, groupId: number) {
const { setDay } = useTimetableStore();
const { data, error } = await apiClient.GET('/timetable/event/', {
const { data } = await apiClient.GET('/timetable/event/', {
params: {
query: {
start: stringifyDate(date),
Expand All @@ -113,8 +100,6 @@ export class TimetableApi {
});
if (data && data !== null) {
setDay(date, data.items);
} else {
recordError(error);
}
}

Expand Down
19 changes: 5 additions & 14 deletions src/api/controllers/auth/AuthApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { scopename } from '@/models/ScopeName';
import { useProfileStore } from '@/store/profile';
import { LocalStorage, LocalStorageItem } from '@/models/LocalStorage';
import { UNKNOWN_DEVICE } from '@/models';
import { recordError } from '@/utils/errorHandler';

import router from '@/router';
import apiClient from '@/api/';

Expand All @@ -32,29 +32,24 @@ export type UserSessionById =
export class AuthApi {
static getScopes = apply(async () => {
const { setScopes } = useAuthStore();
const { data, error } = await apiClient.GET('/auth/scope');
const { data } = await apiClient.GET('/auth/scope');
if (data) {
setScopes(data);
} else {
recordError(error);
}
}, [scoped, scopename.auth.scope.read]);

static getUser = apply(
async (id: number, info: UserInfo[] = []) => {
const { setUsers } = useAuthStore();
const { response, data, error } = await apiClient.GET('/auth/user/{user_id}', {
const { data } = await apiClient.GET('/auth/user/{user_id}', {
params: {
path: { user_id: id },
query: { info },
},
});
console.log(response);

if (data) {
setUsers([data]);
} else {
recordError(error);
}
},
[scoped, scopename.auth.user.read]
Expand All @@ -63,13 +58,11 @@ export class AuthApi {
static getUsers = apply(
async (info: UserInfo[] = []) => {
const { setUsers } = useAuthStore();
const { data, error } = await apiClient.GET('/auth/user', {
const { data } = await apiClient.GET('/auth/user', {
params: { query: { info } },
});
if (data) {
setUsers(data.items);
} else {
recordError(error);
}
},
[scoped, scopename.auth.user.read]
Expand All @@ -91,7 +84,7 @@ export class AuthApi {
const promise = apiClient.GET('/auth/me', {
params: { query: { info } },
});
const { data, error } = await promise;
const { data } = await promise;

if (data) {
profileStore.id = data.id;
Expand All @@ -116,8 +109,6 @@ export class AuthApi {
}

profileStore.updateTokenScopes();
} else {
recordError(error);
}

return promise;
Expand Down
15 changes: 8 additions & 7 deletions src/api/controllers/auth/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ToastType } from '@/models';
import router from '@/router';
import { useProfileStore } from '@/store/profile';
import { useToastStore } from '@/store/toast';
import { apiError } from '@/utils/errorHandler';

export type Func<R = any, FuncArgs extends any[] = any[]> = (...args: FuncArgs) => R;
type Decorator<F extends Func = Func, DecoratorArgs extends any[] = any[]> = Func<
Expand Down Expand Up @@ -42,17 +43,17 @@ export function showErrorToast<F extends Func>(
try {
const response = await method(...args);
return response;
} catch (error) {
console.log(error);
} catch (err) {
const error = err as apiError;
if (error) {
toastStore.push({
title: error.msg ?? error.ru,
title: error.ru ?? error.message,
type: ToastType.Error,
});
} else {
toastStore.push({
title: 'Неизвестная ошибка',
description: error instanceof Error ? error.message : '',
description: '',
type: ToastType.Error,
});
}
Expand All @@ -67,9 +68,9 @@ export function checkToken<F extends Func<any, any>>(
try {
const { error } = await apiClient.GET('/auth/me');
throw error;
} catch (error) {
console.log(error);
if (error && error.msg === 'Forbidden') {
} catch (err) {
const error = err as apiError;
if (error && error.message === 'Forbidden') {
const { deleteToken } = useProfileStore();
const toastStore = useToastStore();
deleteToken();
Expand Down
15 changes: 15 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
export * from './controllers';
import { recordError } from '@/utils/errorHandler';
import { createClient } from '@profcomff/api-uilib';
import { type Middleware } from 'openapi-fetch';

const responseMiddleware: Middleware = {
async onResponse({ response }) {
const data = await response.clone();
if (!response.ok) {
const error = await data.json();
recordError(response.url, response.status, await error);
return undefined;
}
return response;
},
};

const apiClient = createClient(import.meta.env.VITE_API_URL);
apiClient.use(responseMiddleware);
export default apiClient;
6 changes: 2 additions & 4 deletions src/components/IrdomAuthButton.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { AuthMethodName } from '@/models';
import { recordError } from '@/utils/errorHandler';
import apiClient from '@/api/';
export interface AuthButton {
Expand All @@ -20,11 +20,9 @@ const props = withDefaults(defineProps<Props>(), { unlink: false });
const authUrl = ref<string>();
onMounted(async () => {
const { data, error } = await apiClient.GET(`/auth/${props.button.method}/auth_url`);
const { data } = await apiClient.GET(`/auth/${props.button.method}/auth_url`);
if (data) {
authUrl.value = data.url;
} else {
recordError(error);
}
});
Expand Down
20 changes: 7 additions & 13 deletions src/components/RegistrationForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import { AuthApi } from '@/api';
import { useToastStore } from '@/store/toast';
import { ref } from 'vue';
import { recordError } from '@/utils/errorHandler';
const toastStore = useToastStore();
Expand All @@ -19,18 +18,13 @@ const submit = async () => {
title: 'Пароли не совпадают',
});
}
const { data, error } = await AuthApi.registerEmail(email.value, password.value);
if (data) {
if (data.status == 'Success') {
toastStore.push({
title: 'Успех!',
description:
'Мы отправили письмо с инструкциями по активации аккаунта на электронную почту',
});
emit('success');
}
} else {
recordError(error);
const { data } = await AuthApi.registerEmail(email.value, password.value);
if (data && data.status == 'Success') {
toastStore.push({
title: 'Успех!',
description: 'Мы отправили письмо с инструкциями по активации аккаунта на электронную почту',
});
emit('success');
}
};
</script>
Expand Down
6 changes: 2 additions & 4 deletions src/router/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useProfileStore } from '@/store/profile';
import { useToastStore } from '@/store/toast';
import { AuthApi } from '@/api';
import { AuthMethodName } from '@/models';
import { recordError } from '@/utils/errorHandler';

import apiClient from '@/api/';

export const authRoutes: RouteRecordRaw[] = [
Expand Down Expand Up @@ -63,7 +63,7 @@ export const authHandler: NavigationGuard = async to => {
replace: true,
};
}
const { data, error } = profileStore.isUserLogged
const { data } = profileStore.isUserLogged
? await apiClient.POST(`/auth/${methodName}/registration`, {
body: {
...to.query,
Expand All @@ -82,8 +82,6 @@ export const authHandler: NavigationGuard = async to => {
profileStore.updateToken();
toastStore.push({ title: 'Вы успешно вошли в аккаунт' });
return { path: '/profile', replace: true };
} else {
recordError(error);
}
return { path: '/auth/error', query: { text: 'Непредвиденная ошибка' }, replace: true };
} catch (error) {
Expand Down
5 changes: 1 addition & 4 deletions src/store/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { LocalStorage, LocalStorageItem } from '@/models/LocalStorage';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import apiClient from '@/api/';
import { recordError } from '@/utils/errorHandler';

export const useProfileStore = defineStore('profile', () => {
const id = ref<number | null>(null);
Expand Down Expand Up @@ -57,7 +56,7 @@ export const useProfileStore = defineStore('profile', () => {
if (newMarketingId) {
marketingId.value = newMarketingId;
} else if (item === null) {
const { data, error } = await apiClient.POST('/marketing/v1/user');
const { data } = await apiClient.POST('/marketing/v1/user');
if (data) {
LocalStorage.set(LocalStorageItem.MarketingId, data.id);
marketingId.value = data.id;
Expand All @@ -68,8 +67,6 @@ export const useProfileStore = defineStore('profile', () => {
additional_data: JSON.stringify(data),
},
});
} else {
recordError(error);
}
} else {
marketingId.value = +item;
Expand Down
Loading

0 comments on commit eeba2b7

Please sign in to comment.