Blog posts working now

This commit is contained in:
Michal Vanko 2023-01-31 20:04:22 +01:00
parent eafc8b7082
commit b3153ae06a
5 changed files with 51 additions and 61 deletions

View File

@ -1,17 +0,0 @@
<script lang="ts">
import ArticleFooter from '../../components/blog/ArticleFooter.svelte'
import { contentClass } from './blog.css'
export let post
</script>
<svelte:head>
<title>{post.title}</title>
</svelte:head>
<h1>{post.title}</h1>
<div class="content {contentClass}">
{@html post.body}
</div>
<ArticleFooter {post} />

View File

@ -1,44 +0,0 @@
import { readFile } from 'fs'
import { promisify } from 'util'
import fm from 'front-matter'
import { parseField } from '../../markdown/parse-markdown'
import type { PostAttributes } from './content'
import type { Request, Response } from '@sveltejs/kit'
export interface SinglePost {
body: string
}
export async function get({ params: { slug } }: Request): Promise<Response> {
// the `slug` parameter is available because
// this file is called [slug].json.js
let postSource: string
try {
postSource = await promisify(readFile)(`_posts/blog/${slug}.md`, 'utf-8')
} catch (e) {
if (e.code === 'ENOENT') {
return {
status: 404,
body: 'Post not found \n' + e.toString(),
headers: {},
}
}
return {
status: 500,
body: 'Error loading post source file. \n' + e.toString(),
headers: {},
}
}
const parsedPost = fm<PostAttributes>(postSource)
const post = parseField<SinglePost>('body')({
...parsedPost.attributes,
body: parsedPost.body,
})
return {
body: { post },
}
}

View File

@ -0,0 +1,33 @@
import { readFile } from 'fs'
import { promisify } from 'util'
import fm from 'front-matter'
import { parseField } from '../../../markdown/parse-markdown'
import { error, json } from '@sveltejs/kit'
import type { PostAttributes } from '../content'
import type { PageServerLoad } from './$types'
export interface SinglePost {
body: string
}
export const load = (async ({ params: { slug } }) => {
let postSource: string
try {
postSource = await promisify(readFile)(`_posts/blog/${slug}.md`, 'utf-8')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
if (e.code === 'ENOENT') {
throw error(404, 'Post not found \n' + e.toString())
}
throw e
}
const parsedPost = fm<PostAttributes>(postSource)
const post = parseField<SinglePost>('body')({
...parsedPost.attributes,
body: parsedPost.body,
})
return post
}) satisfies PageServerLoad

View File

@ -0,0 +1,18 @@
<script lang="ts">
import ArticleFooter from '../../../components/blog/ArticleFooter.svelte'
import type { PageData } from './$types'
import { contentClass } from './blog.css'
export let data: PageData
</script>
<svelte:head>
<title>{data.title}</title>
</svelte:head>
<h1>{data.title}</h1>
<div class="content {contentClass}">
{@html data.body}
</div>
<ArticleFooter post={data} />