Replies: 1 comment
|
The part that caught me is that const reviveDates = (_key: string, value: unknown) =>
typeof value === "string" &&
/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d/.test(value)
? new Date(value)
: value;
class ReviverResponse extends Response {
async json() {
return JSON.parse(await this.text(), reviveDates);
}
}
const dateMiddleware = {
async onResponse({ response }: { response: Response }) {
if (!response.headers.get("content-type")?.includes("application/json")) {
return;
}
const body = await response.text();
const headers = new Headers(response.headers);
headers.set(
"content-length",
String(new TextEncoder().encode(body).byteLength),
);
return new ReviverResponse(body, {
status: response.status,
statusText: response.statusText,
headers,
});
},
};
client.use(dateMiddleware);I tested this with the current package and the parsed date is a |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
My API returns dates as ISO strings. Obviously I don't want to parse it everywhere on the go and thus want to to adjust the parsing of the response.
The default
Response.json()method has no overload to adjust the parsing likeJSON.parse(string, (key, value) => {})thus one had to use.text()and parse the result manually. How can I archive this with theopenapi-fetchlibrary?I tried the following:
but sadly the static method
Response.json()does convert any given object to a string and back thus killing all custom parsing. The library checks the response for a correctResponseobject viainstanceofand thus I can't return a custom object with the correct structure (the code just crashes without any error and the webpage is broken).How can I customize the response parsing?
All reactions