Repository navigation
Replies: 2 comments
|
+1 on this one |
|
You can wrap the returned promise instead of reimplementing all the generic async function requireData<T>(
pending: Promise<{ data?: T; error?: unknown; response: Response }>,
) {
const { data, error, response } = await pending;
if (!response.ok) {
throw new Error(`HTTP ${response.status}`, { cause: error });
}
if (data === undefined) {
throw new Error(`Expected a response body, received HTTP ${response.status}`);
}
return data;
}
const user = await requireData(client.GET('/users/{id}', {
params: { path: { id: '123' } },
}));
// Inferred response body type, without undefined.The missing-body check matters even with your middleware: a successful Your middleware can stay in place. Exceptions it throws propagate through this helper; the explicit HTTP check also makes the helper usable without it. Middleware changes runtime behavior, but it doesn't change the client's declared success/error return union. Checked with |
Uh oh!
There was an error while loading. Please reload this page.
Hello there 👋
I created a Middleware which automatically throws on all HTTP errors.
This ensures that only 2xx requests are received directly by my client.
This currently requires me to always check if the error object in the response exists -> only then the type is narrowed down from
SomeResponseType | undefinedto justSomeResponseType.I tried building a wrapper which removes the undefined from the return type of the GET/PUT/POST/DELETE functions, but was unsuccessful after many attempts :/
Do you have advice or is there a better way to archive this? :)
All reactions