feat(content-blog): parse date from middle of file path (#6245)

This commit is contained in:
Joshua Chen 2022-01-20 16:43:00 +08:00 committed by GitHub
parent 29ecf22409
commit d133910cb2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 44 additions and 18 deletions

View file

@ -108,4 +108,26 @@ describe('parseBlogFileName', () => {
slug: '/2021/05/12/announcing-docusaurus-two-beta/subfolder/subfile',
});
});
test('parse date in the middle of path', () => {
expect(
parseBlogFileName('team-a/2021/05/12/announcing-docusaurus-two-beta.md'),
).toEqual({
date: new Date('2021-05-12Z'),
text: 'announcing-docusaurus-two-beta',
slug: '/2021/05/12/team-a/announcing-docusaurus-two-beta',
});
});
test('parse date in the middle of a folder name', () => {
expect(
parseBlogFileName(
'team-a-2021-05-12-hey/announcing-docusaurus-two-beta.md',
),
).toEqual({
date: new Date('2021-05-12Z'),
text: 'hey/announcing-docusaurus-two-beta',
slug: '/2021/05/12/team-a-hey/announcing-docusaurus-two-beta',
});
});
});

View file

@ -63,7 +63,7 @@ export function getBlogTags(blogPosts: BlogPost[]): BlogTags {
}
const DATE_FILENAME_REGEX =
/^(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(\/index)?.mdx?$/;
/^(?<folder>.*)(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(\/index)?.mdx?$/;
type ParsedBlogFileName = {
date: Date | undefined;
@ -76,12 +76,11 @@ export function parseBlogFileName(
): ParsedBlogFileName {
const dateFilenameMatch = blogSourceRelative.match(DATE_FILENAME_REGEX);
if (dateFilenameMatch) {
const dateString = dateFilenameMatch.groups!.date!;
const text = dateFilenameMatch.groups!.text!;
const {folder, text, date: dateString} = dateFilenameMatch.groups!;
// Always treat dates as UTC by adding the `Z`
const date = new Date(`${dateString}Z`);
const slugDate = dateString.replace(/-/g, '/');
const slug = `/${slugDate}/${text}`;
const slug = `/${slugDate}/${folder}${text}`;
return {date, text, slug};
} else {
const text = blogSourceRelative.replace(/(\/index)?\.mdx?$/, '');