import fs from 'fs' ; import { join } from 'path' ; import matter from 'gray-matter' ; import { BlogApi , BlogPost } from './blog-api' ; const latestPostsLimit = 5 ; const postsDirectory = join ( process . cwd ( ) , 'src/_posts' ) ; function getRawPostBySlug ( slug ) { const fullPath = join ( postsDirectory , `${ slug }.mdx` ) ; const fileContents = fs . readFileSync ( fullPath , 'utf8' ) ; return matter ( fileContents ) ; } function getAllSlugs ( ) { return fs . readdirSync ( postsDirectory ) ; } function getPostBySlug ( slug , fields = [ ] ) { const realSlug = slug . replace ( /\.mdx$/ , '' ) ; const { data , content } = getRawPostBySlug ( realSlug ) ; const items = { } ; fields . forEach ( ( field ) => { if ( field === 'slug' ) { items [ field ] = realSlug ; } if ( field === 'content' ) { items [ field ] = content ; } if ( data [ field ] ) { items [ field ] = data [ field ] ; } } ) ; return items ; } function getAllPosts ( fields = [ ] ) { return ( getAllSlugs ( ) . map ( ( slug ) => getPostBySlug ( slug , fields ) ) . sort ( ( post1 , post2 ) => ( post1 . date > post2 . date ? - 1 : 1 ) ) ) ; } function getLatestPosts ( fields = [ ] ) { return getAllPosts ( fields ) . slice ( 0 , latestPostsLimit ) ; } function getPostsByTag ( tag , fields = [ ] ) { return getAllPosts ( fields ) . filter ( ( post ) => { const tags = post . tags ?? [ ] ; return tags . includes ( tag ) ; } ) ; } function getAllTags ( ) { const posts = getAllPosts ( [ 'tags' ] ) ; const allTags = new Set < string > ( ) ; posts . forEach ( ( post ) => { const tags = post . tags as Array < string > ; tags . forEach ( ( tag ) => allTags . add ( tag ) ) ; } ) ; return Array . from ( allTags ) ; } export const blogApi = { getRawPostBySlug , getAllSlugs , getAllPosts , getLatestPosts , getPostsByTag , getPostBySlug , getAllTags , } ;