SOrting and filtering of posts

This commit is contained in:
2020-01-17 19:53:22 +01:00
parent 78a5fb6ef5
commit 64959808ee
3 changed files with 135 additions and 11 deletions

View File

@ -1,18 +1,16 @@
import { readdir, readFile } from 'fs'
import { promisify } from 'util'
import { basename } from 'path'
import { pipe, partial, prop, sortBy, reverse } from 'ramda'
import fm from 'front-matter'
import marked from 'marked'
const { NODE_ENV } = process.env
export async function get(req, res) {
const { tag } = req.query
const files = await promisify(readdir)(`_posts/blog/`, 'utf-8')
const filteredFiles =
NODE_ENV !== 'production'
? files
: files.filter(file => !file.startsWith('dev-'))
const filteredFiles = filterDevelopmentFiles(files)
const contents = await Promise.all(
filteredFiles.map(async file => {
@ -36,10 +34,24 @@ export async function get(req, res) {
}
})
)
const filteredContents = pipe(
sortBy(prop('date')),
reverse,
partial(filterByTag, [tag])
)(contents)
res.writeHead(200, {
'Content-Type': 'application/json',
})
res.end(JSON.stringify(contents))
res.end(JSON.stringify(filteredContents))
}
function filterDevelopmentFiles(files) {
return NODE_ENV !== 'production'
? files
: files.filter(file => !file.startsWith('dev-'))
}
function filterByTag(tag, contents) {
return tag ? contents.filter(content => content.tags.includes(tag)) : contents
}

View File

@ -1,9 +1,15 @@
<script context="module">
export function preload({ params, query }) {
return this.fetch(`blog.json`)
const blogQuery = query
? '?' +
Object.entries(query)
.map(q => q.join('='))
.join('&')
: ''
return this.fetch(`blog.json${blogQuery}`)
.then(r => r.json())
.then(posts => {
return { posts }
return { posts, query }
})
}
</script>
@ -12,6 +18,7 @@
import { format } from 'date-fns'
export let posts
export let query
</script>
<style>
@ -54,14 +61,33 @@
.lighten {
color: #595a8f;
}
.see-all {
text-align: end;
margin-top: -1.5em;
}
</style>
<svelte:head>
<title>My blog @michalvankodev</title>
</svelte:head>
<h1>Recent posts</h1>
{#if posts.length === 0}
<p class="no-posts">You've found void in the space.</p>
{:else}
<h1>
Recent
{#if query.tag}
<em>{query.tag}</em>
{/if}
posts
</h1>
{#if query.tag}
<div class="see-all">
<a href="/blog" class="">See all posts</a>
</div>
{/if}
{/if}
<ul class="post-list">
{#each posts as post}
<!-- we're using the non-standard `rel=prefetch` attribute to