-
Notifications
You must be signed in to change notification settings - Fork 7
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
Repeated pattern in components interacting with models #32
Comments
for example async function submit() {
const [data, error] = await wrapper("my_promise")
}
async function wrapper(myPromise) {
try {
const data = await myPromise()
return [data, null]
} catch (error) {
return [null, error?.response?.data?.message || "Unknown error"]
}
} |
Related to #42 |
我可以試著處理看看這一項 |
@laporchen 上次看這部分有什麼想法嗎? 我覺得初步可以先從抽出 catch (error) 這一塊開始,例如我想到的是改寫成 .then().catch() 然後 catch() 裡放一個 reuse 的 error handling function |
This is what I worked on. import axios from "axios";
interface RequestHandler<T extends Function> {
callback: T;
parameters: T extends (...args: infer U) => unknown ? U : never;
}
function axiosErrorWrapper(error: unknown): string {
if (axios.isAxiosError(error) && error.response?.data?.message) {
return error.response.data.message;
}
return "Unknown error occurred :(";
}
export async function axiosRequestWrapper<
F extends Function,
R extends F extends (...args: unknown[]) => infer R ? R : never,
>(req: RequestHandler<F>): Promise<[null, string] | [R, null]> {
let res: R;
try {
if (req.parameters) {
res = await req.callback(...req.parameters);
} else {
res = req.callback();
}
} catch (error) {
const errorMsg = axiosErrorWrapper(error);
return [null, errorMsg];
}
return [res, null];
}
/* now we can request like this now
const [res, error] = await axiosRequestWrapper({
callback: () => {
return { data: "hello" };
},
parameters: [],
});
if (error === null) {
console.log("got res", res.data);
} else {
console.log("got error :(", error);
}
*/ |
這是個蠻好的包裝,我之前想很久要不要這樣寫,直到我後來想到,我們現在在一個元件裡如果有這樣的 API Call 所以如果要這樣整個包起來(callback, parameters...)我會傾向用 composable (useXXX),然後連 isLoading 跟 errorMsg 都由 composable 提供,簡單來說會長得類似 useAxios
|
總結一下,我傾向寫一個 |
最近在學 Nuxt.js,發現它的 附上官方範例: const { data, pending, error, refresh } = await useAsyncData(
'mountains',
() => $fetch('https://api.nuxtjs.dev/mountains')
) |
每個有做 POST/PUT/DELETE 的元件都會有這段 pattern 出現,可以討論是否適合包成 hook
至少 catch 那邊的邏輯可以抽出來
new-front-end/src/pages/course/[name]/announcements/new.vue
Lines 33 to 53 in c77be18
The text was updated successfully, but these errors were encountered: