Bir işlevim var takes keyfi bir async işlevi alır ve bu async işlevini beklemenin sonucunu döndürür, ancak bazı ek mantık ekleyen bir try/catch içine sarılır. Ts oyun alanına bakın.
const with401Redirection =
<T extends (...args: any[]) => Promise<any>>(
call: T
): ((...args: Parameters<T>) => ReturnType<T>) =>
// @ts-expect-error
async (...args: Parameters<T>): ReturnType<T> => {
try {
return await call(...args);
} catch (error) {
if ((error as any).httpStatus === 401) {
// do some stuff here
}
throw error;
}
};
interface User {
id: string;
name: string;
}
interface ItemPayload {
field1: string;
field2: string;
}
interface ItemResponse {
id: string;
field1: string;
field2: string;
}
const client = {
get<ResponseType>(url: string): Promise<ResponseType> {
// logic to hit server and return result here
return '' as any;
},
post<ResponseType>(url: string, body: Record<string, any>): Promise<ResponseType> {
// logic to hit server and return result here
return '' as any;
}
};
const getUser = with401Redirection(() =>
client.get<User>('url_1')
);
const saveItem = with401Redirection((body: ItemPayload) =>
client.post<ItemResponse>('url_2', body)
);
Ben gibi hissediyorum // @ts-expect-error
içinde with401Redirection
gerekli olmamalı - bunu nasıl kaldırabilirim veya genel olarak yazmayı nasıl temizleyebilirim with401Redirection
işlev mi? Aklınızda bulunsun, bu gerçeği korumak istiyorum. getUser
ve saveItem
işlevlerin türleri benim için otomatik olarak çıkarıldı.