Skip to content

Commit

Permalink
#8 Implements ArticlePreview component
Browse files Browse the repository at this point in the history
  • Loading branch information
raeperd committed Jan 9, 2022
1 parent 4f04bb5 commit fd2089b
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 53 deletions.
47 changes: 0 additions & 47 deletions lib/api.ts

This file was deleted.

8 changes: 8 additions & 0 deletions lib/article.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { getAllArticles } from './article';

test('getAllArticles', () => {
const articles = getAllArticles()
expect(articles).toHaveLength(5)

expect(articles[0].title?.length).toBeGreaterThanOrEqual(0)
})
34 changes: 34 additions & 0 deletions lib/article.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { join } from 'path';
import { readdirSync, readFileSync, statSync } from 'fs';
import matter from 'gray-matter';

const ARTICLE_DIRECTORY = join(process.cwd(), 'lib', 'content', 'post')

export function getAllArticles(): Article[] {
return readdirSync(ARTICLE_DIRECTORY)
.filter((file) => !file.startsWith('_'))
.map((file) => readArticleSync(file))
}

function readArticleSync(file: string): Article {
const filePath = join(ARTICLE_DIRECTORY, file)
const fileContent = readFileSync(filePath, 'utf8')
const { data, content } = matter(fileContent)
return {
slug: file.replace(/\.md$/, ''),
title: data.title,
date: data.date
? data.date.toDateString()
: statSync(filePath).birthtime.toDateString(),
tags: data.tags ? data.tags : [],
content,
}
}

export interface Article {
slug: string,
title?: string,
date: string,
tags: string[],
content: string
}
31 changes: 25 additions & 6 deletions pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
import Head from 'next/head';
import { Article, getAllArticles } from '../lib/article';

export default function Index({ siteName }: {siteName: string}) {
export default function Index({ siteName, posts }: IndexProps) {
return (
<Head>
<title>{siteName}</title>
</Head>
<>
<Head>
<title>{siteName}</title>
</Head>
{posts.map((post) => <ArticlePreview article={post} />)}
</>
)
}

export async function getStaticProps() {
function ArticlePreview({ article }: {article: Article}) {
return (
// TODO: ADD LINK
<article className="post-entry" key={article.slug}>
<h2>{article.title}</h2>
<time>{article.date}</time>
</article>
)
}

type IndexProps = {
siteName: string,
posts: Article[]
}

export async function getStaticProps(): Promise<{props: IndexProps}> {
const siteName = process.env.SITE_NAME ? process.env.SITE_NAME : 'Paper'
return { props: { siteName } }
return { props: { siteName, posts: getAllArticles() } }
}

0 comments on commit fd2089b

Please sign in to comment.