2022-04-24 04:27:51 +00:00
|
|
|
const fs = require('fs');
|
|
|
|
const matter = require('gray-matter');
|
|
|
|
const { join } = require('path');
|
2022-02-14 20:32:58 +00:00
|
|
|
|
2022-04-27 08:03:21 +00:00
|
|
|
const postsDir = join(process.cwd(), 'posts');
|
|
|
|
const cacheDir = join(process.cwd(), '.next', 'cache');
|
|
|
|
const publicDir = join(process.cwd(), 'public');
|
2022-02-14 20:32:58 +00:00
|
|
|
|
2022-04-24 04:27:51 +00:00
|
|
|
function getPost(rawslug, filter = []) {
|
2022-02-14 20:32:58 +00:00
|
|
|
const slug = rawslug.replace(/\.md$/, '');
|
2022-04-27 08:03:21 +00:00
|
|
|
const path = join(postsDir, `${slug}.md`);
|
2022-02-14 20:32:58 +00:00
|
|
|
const file = fs.readFileSync(path, 'utf-8');
|
|
|
|
const { data, content } = matter(file);
|
|
|
|
|
|
|
|
if (data['last_updated'] === undefined)
|
|
|
|
data['last_updated'] = data['created_at'];
|
|
|
|
|
|
|
|
if (filter.length === 0)
|
|
|
|
return { ...data, content, slug, rawslug };
|
|
|
|
|
2022-04-24 04:27:51 +00:00
|
|
|
let post = {};
|
2022-02-14 20:32:58 +00:00
|
|
|
for (const [_, entry] of filter.entries()) {
|
|
|
|
if (entry === 'slug')
|
|
|
|
post[entry] = slug;
|
|
|
|
|
|
|
|
if (entry === 'rawslug')
|
|
|
|
post[entry] = rawslug;
|
|
|
|
|
|
|
|
if (entry === 'content')
|
|
|
|
post[entry] = content;
|
|
|
|
|
|
|
|
if (typeof data[entry] !== 'undefined') {
|
|
|
|
post[entry] = data[entry]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return post;
|
|
|
|
}
|
|
|
|
|
2022-04-24 04:27:51 +00:00
|
|
|
function getAllPosts(filter = []) {
|
2022-04-27 08:03:21 +00:00
|
|
|
const files = fs.readdirSync(postsDir);
|
2022-02-14 20:32:58 +00:00
|
|
|
|
2022-04-23 23:03:43 +00:00
|
|
|
return files
|
2022-04-24 04:27:51 +00:00
|
|
|
.filter(c => !c.match(/^\./))
|
|
|
|
.map(file => {
|
|
|
|
return getPost(file, filter)
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-04-27 08:03:21 +00:00
|
|
|
|
|
|
|
function cachePostsMeta() { // public access cache
|
|
|
|
const posts = getAllPosts(['title', 'slug', 'created_at', 'last_updated']);
|
|
|
|
fs.writeFile(join(publicDir, 'posts.json'), JSON.stringify(posts), (e) => {
|
|
|
|
if (e)
|
|
|
|
console.error(e);
|
|
|
|
});
|
|
|
|
return posts;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getPostsMeta() {
|
|
|
|
const file = fs.readFileSync(join(publicDir, 'posts.json'), 'utf-8');
|
|
|
|
|
|
|
|
if (!file) {
|
|
|
|
return cachePostsMeta();
|
|
|
|
}
|
|
|
|
|
|
|
|
return JSON.parse(file);
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = { getAllPosts, getPost, getPostsMeta, cachePostsMeta };
|