guardz-event
Version:
Type-safe event handling with runtime validation using guardz for unsafe data from 3rd parties
111 lines • 4.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeCustomEventListener = safeCustomEventListener;
const guardz_1 = require("guardz");
const Status_1 = require("../../domain/event/Status");
/**
* Safe CustomEvent listener with callback-based API
* Usage: element.addEventListener('custom-event', safeCustomEventListener(isCustomData, { onSuccess: handleCustomData }));
*/
function safeCustomEventListener(guard, config) {
return (event) => {
const result = executeCustomEventValidation(event, {
guard,
tolerance: config.tolerance,
allowedOrigins: config.allowedOrigins,
allowedSources: config.allowedSources,
onError: (error, context) => {
// In tolerance mode, call onTypeMismatch for validation errors
if (config.tolerance && context.type === 'validation' && config.onTypeMismatch) {
config.onTypeMismatch(error);
}
else if (config.onError) {
config.onError(error, context);
}
}
});
if (result.status === Status_1.Status.SUCCESS) {
config.onSuccess(result.data);
}
else {
if (result.code === 500 && config.onTypeMismatch) {
config.onTypeMismatch(result.message);
}
else if (config.onError) {
config.onError(result);
}
}
};
}
/**
* Execute CustomEvent validation with the given configuration
*/
function executeCustomEventValidation(event, config) {
try {
// Extract data from CustomEvent
const data = event.detail;
// Validate event structure
if (config.validateEvent && (typeof data === 'undefined' || data === null)) {
const errorMessage = 'CustomEvent has no detail';
if (config.onError) {
config.onError(errorMessage, {
type: 'validation',
eventType: event.type || 'custom'
});
}
return {
status: Status_1.Status.ERROR,
code: 400,
message: errorMessage
};
}
// Type validation
const validationResult = config.tolerance
? (0, guardz_1.guardWithTolerance)(data, config.guard, {
identifier: config.identifier || `CustomEvent (${event.type || 'custom'})`,
callbackOnError: (error) => {
if (config.onError) {
config.onError(error, {
type: 'validation',
eventType: event.type || 'custom'
});
}
}
})
: config.guard(data);
if (!validationResult) {
const errorMessage = `CustomEvent validation failed: ${config.identifier || `CustomEvent (${event.type || 'custom'})`}`;
if (config.onError) {
config.onError(errorMessage, {
type: 'validation',
eventType: event.type || 'custom'
});
}
return {
status: Status_1.Status.ERROR,
code: 500,
message: errorMessage
};
}
return {
status: Status_1.Status.SUCCESS,
data: data
};
}
catch (error) {
const errorMessage = `CustomEvent validation error: ${error instanceof Error ? error.message : 'Unknown error'}`;
if (config.onError) {
config.onError(errorMessage, {
type: 'unknown',
eventType: event?.type || 'custom',
originalError: error
});
}
return {
status: Status_1.Status.ERROR,
code: 500,
message: errorMessage
};
}
}
//# sourceMappingURL=CustomEventListener.js.map