Skip to content

Instantly share code, notes, and snippets.

@mohamm6d
Created May 28, 2024 19:11
Show Gist options
  • Save mohamm6d/c016281c385975a54b4a3369ce811a52 to your computer and use it in GitHub Desktop.
Save mohamm6d/c016281c385975a54b4a3369ce811a52 to your computer and use it in GitHub Desktop.
JSON-Validator
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
const API_URL = 'https://dummyjson.com/test';
const POSTMARK_URL = 'https://api.postmarkapp.com/email';
const POSTMARK_API_KEY = '';
const EMAIL_PAYLOAD_TEMPLATE = {
"From": "[email protected]",
"To": "[email protected]",
"Subject": "API Validation Failed",
"TextBody": ''
};
/**
* Main handler for the fetch event.
* @param {Request} request - The incoming request object.
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
try {
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error(`Failed to fetch API data: ${response.statusText}`);
}
const data = await response.json();
const validationError = validateJson(data);
if (validationError) {
await sendEmailAlert(validationError);
return new Response('Validation failed. Email alert sent.', { status: 200 });
}
return new Response('Validation successful.', { status: 200 });
} catch (error) {
console.error('Error during request handling:', error);
return new Response(`Error: ${error.message}`, { status: 500 });
}
}
/**
* Validates the JSON data from the API response.
* @param {Object} data - The JSON data to validate.
* @returns {string|null} - An error message if validation fails, otherwise null.
*/
function validateJson(data) {
if (!data || typeof data !== 'object' || !data.requiredField) {
return 'Validation failed: requiredField is missing.';
}
return null;
}
/**
* Sends an email alert using the Postmark API.
* @param {string} errorMessage - The error message to include in the email body.
* @returns {Promise<void>}
*/
async function sendEmailAlert(errorMessage) {
const emailPayload = { ...EMAIL_PAYLOAD_TEMPLATE, TextBody: `The API response validation failed with the following error: ${errorMessage}` };
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Postmark-Server-Token': POSTMARK_API_KEY
},
body: JSON.stringify(emailPayload)
};
const response = await fetch(POSTMARK_URL, requestOptions);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to send email alert: ${response.statusText} - ${errorText}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment