(
response: Response,
schema: T,
)
| 88 | } |
| 89 | |
| 90 | const parseResponseBody = async <T extends z.ZodTypeAny>( |
| 91 | response: Response, |
| 92 | schema: T, |
| 93 | ): Promise<z.infer<T> | ServiceError> => { |
| 94 | let body: unknown; |
| 95 | try { |
| 96 | body = await response.json(); |
| 97 | } catch (error) { |
| 98 | return { |
| 99 | statusCode: StatusCodes.INTERNAL_SERVER_ERROR, |
| 100 | errorCode: ErrorCode.INVALID_RESPONSE_BODY, |
| 101 | message: `Failed to parse response body as JSON: ${error instanceof Error ? error.message : String(error)}`, |
| 102 | }; |
| 103 | } |
| 104 | |
| 105 | if (isServiceError(body)) { |
| 106 | return body; |
| 107 | } |
| 108 | |
| 109 | const parsed = schema.safeParse(body); |
| 110 | if (!parsed.success) { |
| 111 | return { |
| 112 | statusCode: StatusCodes.INTERNAL_SERVER_ERROR, |
| 113 | errorCode: ErrorCode.INVALID_RESPONSE_BODY, |
| 114 | message: `Response body failed schema validation: ${parsed.error.message}`, |
| 115 | }; |
| 116 | } |
| 117 | |
| 118 | return parsed.data; |
| 119 | } |
no test coverage detected