Skip to content

Commit

Permalink
update type response
Browse files Browse the repository at this point in the history
  • Loading branch information
ngocle2497 committed Jul 11, 2022
1 parent 842cacf commit 5d014be
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 8 deletions.
13 changes: 13 additions & 0 deletions template/src/app/common/method/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,19 @@ export const propsToStyle = <T = Record<string, number | string>>(
}, {} as Record<string, number | string>);
};

/**
* return true when success and false when error
*/
export const handleErrorResponse = (
response: ResponseBase<any>,
): response is ResponseBase<any, true> => {
if (!response.status) {
// TODO: handle error
return false;
}
return true;
};

export const execFunc = <Fn extends (...args: any[]) => any>(
func?: Fn,
...args: Parameters<Fn>
Expand Down
16 changes: 10 additions & 6 deletions template/src/app/config/type.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
export interface ResponseBase<T = Record<string, unknown>> {
export type ResponseBase<T = any, TStatus = boolean> = {
code: number;
} & (TStatus extends true
? {
data: T;

msg?: string | null;
status: true;
}
: {
status: false;

data?: T;

status: boolean;
}
msg?: string |null;

});
export interface ParamsNetwork {
url: string;
params?: Record<string, string | number>;
Expand Down
3 changes: 1 addition & 2 deletions template/src/app/library/networking/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const responseDefault: ResponseBase<Record<string, unknown>> = {
code: -500,
status: false,
msg: translate('error:errorData'),
data: {},
};

export const onPushLogout = async () => {
Expand All @@ -28,7 +27,7 @@ export const handleResponseAxios = <T = Record<string, unknown>>(
res: AxiosResponse<T>,
): ResponseBase<T> => {
if (res.data) {
return { code: CODE_SUCCESS, status: true, data: res.data, msg: null };
return { code: CODE_SUCCESS, status: true, data: res.data, };
}
return responseDefault as ResponseBase<T>;
};
Expand Down
4 changes: 4 additions & 0 deletions template/src/app/redux/listener/login.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { handleErrorResponse } from '@common'
import { takeLatestListeners } from '@listener';
import { ApiConstants, NetWorkService } from '@networking';

Expand All @@ -16,5 +17,8 @@ takeLatestListeners(true)({
if (!response) {
return;
}
if (handleErrorResponse(response)) {
// TODO: do something when login success
}
},
});

0 comments on commit 5d014be

Please sign in to comment.