shadowfacts.net/lib/generate/paginated.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2019-01-04 18:14:53 +00:00
import path from "path";
import ejs from "ejs";
import formatDate from "date-fns/format";
import * as util from "../util";
import * as metadata from "../metadata";
import { Page, PostMetadata } from "../metadata";
import layout from "../layout";
export default async function generatePaginted(posts: Page[], basePath: string, templatePath: string, extraData?: object, extraMetadata?: object) {
const page = await metadata.get(templatePath);
if (extraMetadata) page.metadata = {...page.metadata, ...extraMetadata};
posts = posts.sort((a, b) => {
const aDate = <Date>(<PostMetadata>a.metadata).date;
const bDate = <Date>(<PostMetadata>b.metadata).date;
return bDate.getTime() - aDate.getTime();
});
const chunks = util.chunk(posts, 5);
for (const {chunk, index} of chunks) {
const pageNum = index + 1;
let data = {
metadata: page.metadata,
posts: chunk,
pagination: {
current: pageNum,
total: chunks.length,
prevLink: pageNum == 1 ? "" : pageNum == 2 ? basePath : path.join(basePath, (pageNum - 1).toString()),
nextLink: pageNum == chunks.length ? "" : path.join(basePath, (pageNum + 1).toString())
},
formatDate
};
if (extraData) data = {...data, ...extraData};
let renderedTemplate = ejs.render(page.text, data, {
filename: templatePath
});
renderedTemplate = await layout(renderedTemplate, page.metadata, page.metadata.layout!);
util.write(path.join(basePath, pageNum.toString(), "index.html"), renderedTemplate);
if (pageNum == 1) {
util.write(path.join(basePath, "index.html"), renderedTemplate);
}
}
}