@aws-lambda-powertools/parser
Version:
The parser package for the Powertools for AWS Lambda (TypeScript) library.
39 lines (38 loc) • 1.39 kB
JavaScript
import { ParseError } from './errors.js';
// Implementation
function parse(data, envelope, schema, safeParse) {
if (envelope && safeParse) {
// biome-ignore lint/suspicious/noExplicitAny: at least for now, we need to broaden the type because the envelope's parse and safeParse methods are not typed with StandardSchemaV1 but with ZodSchema
return envelope.safeParse(data, schema);
}
if (envelope) {
// biome-ignore lint/suspicious/noExplicitAny: at least for now, we need to broaden the type because the envelope's parse and safeParse methods are not typed with StandardSchemaV1 but with ZodSchema
return envelope.parse(data, schema);
}
const result = schema['~standard'].validate(data);
/* v8 ignore next -- @preserve */
if (result instanceof Promise) {
throw new ParseError('Schema parsing supports only synchronous validation');
}
if (result.issues) {
const error = new ParseError('Failed to parse schema', {
cause: result.issues,
});
if (safeParse) {
return {
success: false,
error,
originalEvent: data,
};
}
throw error;
}
if (safeParse) {
return {
success: true,
data: result.value,
};
}
return result.value;
}
export { parse };