fix capi response types, improve log clarity

This commit is contained in:
Elijah Duffy
2025-12-22 16:57:06 -08:00
parent 93e5c35d86
commit af1b66649b
6 changed files with 74 additions and 70 deletions

View File

@@ -31,7 +31,8 @@ export class CAPIClient {
}
/**
* Sends CAPIEvents to the server endpoint.
* Sends CAPIEvents to the server endpoint. If no consent is given, no events
* are sent and a dummy response is returned.
* @param events - The array of CAPIEvents to send.
* @returns A promise that resolves to the server response.
* @throws Will throw an error if input or response shape validation fails.
@@ -43,10 +44,8 @@ export class CAPIClient {
console.warn(`[CAPIClient] Consent not given. Skipping sending ${events.length} event(s).`);
}
return {
pixelID: '',
fbTraceID: '',
receivedEvents: 0,
processedEvents: 0,
fbtrace_id: '',
events_received: 0,
messages: []
};
}
@@ -62,7 +61,11 @@ export class CAPIClient {
return e.toObject();
})
};
v.parse(v.object({ events: v.array(v.any()) }), body); // Validate body shape
try {
v.parse(v.object({ events: v.array(v.any()) }), body); // Validate body shape
} catch (err) {
throw new Error(`[CAPIClient] Invalid request body shape: ${(err as Error).message}`);
}
const response = await fetch(this._href, {
method: 'POST',
@@ -73,12 +76,16 @@ export class CAPIClient {
});
const json = await response.json();
if (response.ok) {
const parsed = v.parse(capiResponseBodySchema, json);
return parsed as CAPIResponseBody;
} else {
const parsed = v.parse(capiErrorBodySchema, json);
return parsed as CAPIErrorBody;
try {
if (response.ok) {
const parsed = v.parse(capiResponseBodySchema, json);
return parsed as CAPIResponseBody;
} else {
const parsed = v.parse(capiErrorBodySchema, json);
return parsed as CAPIErrorBody;
}
} catch (err) {
throw new Error(`[CAPIClient] Invalid response shape: ${(err as Error).message}`);
}
}