shadowfacts.net/lib/generate/paginated.ts

44 lines
1.5 KiB
TypeScript
Raw Normal View History

2019-01-04 18:14:53 +00:00
import path from "path";
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())
2019-01-05 02:59:52 +00:00
}
2019-01-04 18:14:53 +00:00
};
if (extraData) data = {...data, ...extraData};
2019-01-05 02:59:52 +00:00
let renderedTemplate = util.render(page.text, data, templatePath);
2019-01-04 18:14:53 +00:00
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);
}
}
}