pasika 0.10.12 → 0.10.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { ZodType, z } from 'zod';
|
|
2
2
|
|
|
3
|
-
interface ZodFetchOptions<TSchema extends ZodType = never> {
|
|
3
|
+
interface ZodFetchOptions<TSchema extends ZodType = never, TRequestSchema extends ZodType = ZodType> {
|
|
4
4
|
url: string | URL;
|
|
5
5
|
init?: RequestInit;
|
|
6
|
+
requestSchema?: TRequestSchema;
|
|
6
7
|
responseSchema?: TSchema;
|
|
7
8
|
}
|
|
8
9
|
/** The response itself, for a caller whose own response relays a body nothing has read. */
|
|
@@ -15,6 +15,11 @@ function decodeFailureBody(body) {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
async function zodFetch(options) {
|
|
18
|
+
if (options.requestSchema !== void 0) {
|
|
19
|
+
const rawBody = options.init?.body;
|
|
20
|
+
const body2 = typeof rawBody === "string" ? JSON.parse(rawBody) : rawBody;
|
|
21
|
+
options.requestSchema.parse(body2);
|
|
22
|
+
}
|
|
18
23
|
const response = await fetch(options.url, options.init);
|
|
19
24
|
if (!response.ok) {
|
|
20
25
|
const body2 = await response.text();
|
|
@@ -39,7 +44,11 @@ async function zodFetch(options) {
|
|
|
39
44
|
throw new HttpError("The upstream answered without a body to decode.", BAD_GATEWAY);
|
|
40
45
|
}
|
|
41
46
|
const decoded = JSON.parse(body);
|
|
42
|
-
|
|
47
|
+
const responseEnvelopeSchema = z.object({
|
|
48
|
+
data: options.responseSchema,
|
|
49
|
+
message: z.string()
|
|
50
|
+
});
|
|
51
|
+
return responseEnvelopeSchema.parse(decoded).data;
|
|
43
52
|
}
|
|
44
53
|
export {
|
|
45
54
|
zodFetch
|