fix(v2): improve BlogPostFrontMatter schema validation (#4759)

* fix(v2): improve BlogPostFrontMatter schema validation

* Edit doc

* Add deprecate warning message

* minor changes, disable warnings temporarily

* only disable warnings + fix frontmatter date type

Co-authored-by: Nam Hoang Le <nam.hoang.le@mgm-tp.com>
Co-authored-by: slorber <lorber.sebastien@gmail.com>
This commit is contained in:
Nam Hoang Le 2021-05-14 23:52:51 +07:00 committed by GitHub
parent b33ee8226d
commit e092910627
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 326 additions and 72 deletions

View file

@ -31,7 +31,7 @@ describe('validateFrontMatter', () => {
validateFrontMatter(frontMatter, schema),
).toThrowErrorMatchingInlineSnapshot(`"\\"test\\" must be a string"`);
expect(consoleError).toHaveBeenCalledWith(
expect.stringContaining('FrontMatter contains invalid values: '),
expect.stringContaining('The following FrontMatter'),
);
});

View file

@ -106,21 +106,38 @@ export function validateFrontMatter<T>(
frontMatter: Record<string, unknown>,
schema: Joi.ObjectSchema<T>,
): T {
try {
return JoiFrontMatter.attempt(frontMatter, schema, {
convert: true,
allowUnknown: true,
});
} catch (e) {
const {value, error, warning} = schema.validate(frontMatter, {
convert: true,
allowUnknown: true,
abortEarly: false,
});
if (error) {
const frontMatterString = JSON.stringify(frontMatter, null, 2);
const errorDetails = error.details;
const invalidFields = errorDetails.map(({path}) => path).join(', ');
const errorMessages = errorDetails
.map(({message}) => ` - ${message}`)
.join('\n');
logValidationBugReportHint();
console.error(
chalk.red(
`FrontMatter contains invalid values: ${JSON.stringify(
frontMatter,
null,
2,
)}`,
`The following FrontMatter:\n${chalk.yellow(
frontMatterString,
)}\ncontains invalid values for field(s): ${invalidFields}.\n${errorMessages}\n`,
),
);
throw e;
throw error;
}
if (warning) {
const warningMessages = warning.details
.map(({message}) => message)
.join('\n');
console.log(chalk.yellow(warningMessages));
}
return value;
}