Created
February 8, 2024 11:06
-
-
Save amcsi/55e092ad52b6db3916c985c3c431cf5e to your computer and use it in GitHub Desktop.
Response envelope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ResponseEnvelopeYuki<T> = ResponseEnvelopeSuccess<T> | ResponseEnvelopeFailure; | |
type ResponseEnvelopeSuccess<T> = { | |
success: true; | |
} & T; | |
type ResponseEnvelopeFailure = { | |
success: false; | |
errorMessage: string; | |
}; | |
async function myFetch<T>(userId: number): Promise<ResponseEnvelopeYuki<T>> { | |
try { | |
const responseBody = await ((await fetch('url')).json() as Promise<T>); | |
return { | |
...responseBody, | |
success: true, | |
}; | |
} catch (e) { | |
// error handling. | |
throw e; | |
} | |
} | |
myFetch(); | |
type MyCardItemResponse = ResponseEnvelopeYuki<{ | |
items: string[]; | |
}>; | |
async function addCartItem() { | |
return myFetch<MyCardItemResponse>(3434); | |
} | |
async function businessLogic() { | |
const result = await addCartItem(); | |
if (result.success) { | |
console.info(result.items); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment