UNPKG

@aws-lambda-powertools/parser

Version:
40 lines (39 loc) 1.4 kB
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 start */ if (result instanceof Promise) { throw new ParseError('Schema parsing supports only synchronous validation'); } /* v8 ignore stop */ 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 };