This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
Zaimki/server/routes/blog.js

84 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-06-23 10:25:56 -07:00
import { Router } from 'express';
import {handleErrorAsync, shuffle} from "../../src/helpers";
import fs from 'fs';
2021-07-02 16:15:44 -07:00
import { caches } from "../../src/cache";
2021-06-23 10:25:56 -07:00
const router = Router();
router.get('/blog', handleErrorAsync(async (req, res) => {
const posts = await caches.blog.fetch(async () => {
2021-06-23 10:25:56 -07:00
const dir = __dirname + '/../../data/blog';
const posts = [];
fs.readdirSync(dir).forEach(file => {
if (!file.endsWith('.md')) {
return;
}
const slug = file.substring(0, file.length - 3);
const content = fs.readFileSync(dir + '/' + file)
.toString('utf-8')
.split('\n')
.filter(l => !!l);
let title = '', date = '', authorsRaw = '', authors = [], hero = null;
try {
title = content[0].match(/^# (.*)$/)[1];
} catch {
return;
}
try {
[, date, authorsRaw] = content[1].match(/^<small>(\d\d\d\d-\d\d-\d\d) \| ([^|]*).*<\/small>$/);
2021-07-02 11:59:04 -07:00
authors = authorsRaw.split(',').map(a => {
a = a.trim();
let m = a.match(/^\[([^\]]+)]/);
if (m) { return m[1]; }
return a;
});
2021-06-23 10:25:56 -07:00
} catch {
return;
}
try {
2021-07-17 03:42:09 -07:00
const classHeroImages = content.map(x => x.match(/<img src="([^"]+)" class="hero/)).filter(x => !!x);
if (classHeroImages.length) {
hero = classHeroImages[0][1];
throw 'continue';
}
const images = content.map(x => x.match(/^!\[[^\]]*]\(([^)]+)\)$/)).filter(x => !!x);
if (images.length) {
hero = images[0][1];
}
2021-06-23 10:25:56 -07:00
} catch {
}
posts.push({slug, title, date, authors, hero});
});
posts.sort((a, b) => {
2021-06-23 10:25:56 -07:00
if (a.date < b.date) { return 1; }
if (a.date > b.date) { return -1; }
return 0;
});
return posts;
})
if (req.query.shortcuts !== undefined) {
const postsShortcuts = [];
if (global.config.blog && global.config.blog.shortcuts) {
for (let slug of Object.values(global.config.blog.shortcuts)) {
postsShortcuts.push(posts.filter(p => p.slug === slug)[0])
}
}
return res.json(postsShortcuts);
}
return res.json(posts);
2021-06-23 10:25:56 -07:00
}));
export default router;