FetchResponse
A type representing a typed fetch response, which inherits from the native Response.
On top of the properties available in native responses, FetchResponse instances have a reference to the originating
request, accessible via the request property. If the response has a failure status code (4XX or 5XX), an error is
available in the error property.
type FetchResponse<
Schema,
Method,
Path,
ErrorOnly = false,
Redirect = RequestRedirect
>;
Type arguments:
-
Schema:
HttpSchemaThe HTTP schema used for the fetch instance.
-
Method:
stringThe HTTP method of the request that caused the error. Must be one of the methods of the path defined in the schema.
-
Path:
stringThe path of the request that caused the error. Must be one of the paths defined in the schema.
-
ErrorOnly:
booleanIf
true, the response will only include the status codes that are considered errors (4XX or 5XX). -
Redirect:
RequestRedirectThe redirect mode for the request, which can be one of
'follow','error', or'manual'. Defaults to'follow'. Iffolloworerror, the response will not include status codes that are considered redirects (300, 301, 302, 303, 307, and 308).
import { HttpSchema } from '@zimic/http';
import { createFetch } from '@zimic/fetch';
interface User {
id: string;
username: string;
}
type Schema = HttpSchema<{
'/users/:userId': {
GET: {
response: {
200: { body: User };
404: { body: { message: string } };
};
};
};
}>;
const fetch = createFetch<Schema>({
baseURL: 'http://localhost:3000',
});
const response = await fetch(`/users/${userId}`, {
method: 'GET',
});
console.log(response); // FetchResponse<Schema, 'GET', '/users'>
Related:
response.request
The request that originated the response.
Type: FetchRequest<Schema, Method, Path>
const response = await fetch('/users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'me' }),
});
console.log(response.request); // FetchRequest<Schema, 'POST', '/users'>
response.error
An error associated with the response, if you need to throw it to be
handled elsewhere. response.error is always available, even if the response has a 2XX or 3XX status code. Some
noncompliant APIs may return failure responses with status codes other than 4XX or 5XX, or may have different
meanings for certain status codes, so your application can handle those cases as response errors as needed.
Type: FetchResponseError<Schema, Method, Path>
const response = await fetch('/users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'me' }),
});
if (response.status === 404) {
console.error(response.error); // FetchResponseError<Schema, 'POST', '/users'>
}
Related: