src/actions.js (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | "use strict";
const fs = require("fs");
const path = require("path");
const send = require("koa-send");
function home(config, responder, posts) {
const postsArray = Array.from(posts.values());
return async function(ctx, next) {
responder(ctx, config, { posts: postsArray });
};
}
function posts(config, responder, posts) {
const postsArray = Array.from(posts.values());
return async function(ctx, next) {
responder(ctx, config, {
listType: null,
listName: "Posts",
posts: postsArray
});
};
}
function highlightTheme(config) {
const theme = config.posts.code.theme;
const themeFile = path.resolve(
__dirname,
`../node_modules/highlight.js/styles/${theme}.css`
);
if (!fs.existsSync(themeFile)) {
throw new Error(`Couldn't find highlight theme ${theme}`);
}
const css = fs.readFileSync(themeFile, "utf-8");
return async function(ctx, next) {
ctx.type = "css";
ctx.body = css;
};
}
function post(config, responder, posts) {
return async function(ctx, next) {
ctx.assert(posts.has(ctx.params.filename), 404, "Post not found");
const post = posts.get(ctx.params.filename);
responder(ctx, config, { post });
};
}
function tags(config, responder, tags) {
return async function(ctx, next) {
responder(ctx, config, {
tags: tags.keys()
});
};
}
function tag(config, responder, items) {
return async function(ctx, next) {
const tag = ctx.params.name;
ctx.assert(items.has(tag), 404, `tag ${tag} not found`);
responder(ctx, config, {
listType: "tag",
listName: tag,
posts: items.get(tag)
});
};
}
const prefix = /^\/static\//;
async function serveFiles(ctx) {
if (prefix.test(ctx.path)) {
await send(ctx, ctx.path.replace(prefix, ""), {
root: "./static"
});
}
}
module.exports = {
home,
posts,
highlightTheme,
post,
tags,
tag,
serveFiles
};
|