summary refs log tree commit diff
path: root/lib
diff options
context:
space:
mode:
authorPatryk Niedźwiedziński <pniedzwiedzinski19@gmail.com>2021-01-10 09:05:43 +0100
committerGitHub <noreply@github.com>2021-01-10 09:05:43 +0100
commitb358a212fda6be6c43eb864979e1c58bd6f5200e (patch)
tree36a0858f99424571bf9fba978a1ae6a3a12af352 /lib
parent01f77f86cea0a6b2b7b74b2105720ee7142d6767 (diff)
parent3bbeb33e6df1aac21ec2e92931f4628b992f4013 (diff)
downloadkronikarz-b358a212fda6be6c43eb864979e1c58bd6f5200e.tar.gz
kronikarz-b358a212fda6be6c43eb864979e1c58bd6f5200e.zip
Merge pull request #22 from pniedzwiedzinski/pages v2.3.0
Pages
Diffstat (limited to 'lib')
-rw-r--r--lib/generateApi.ts44
1 files changed, 38 insertions, 6 deletions
diff --git a/lib/generateApi.ts b/lib/generateApi.ts
index 0024d9f..c8b20ce 100644
--- a/lib/generateApi.ts
+++ b/lib/generateApi.ts
@@ -49,21 +49,52 @@ export function saveApiEntry(post: Post, path: string) {
   );
 }
 
+//#Source https://bit.ly/2neWfJ2
+function chunk (arr: Array<Post>, size: number): Array<Array<Post>> {
+  return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
+             arr.slice(i * size, i * size + size)
+            );
+}
+
+function parsePosts(post: Post) {
+  const apiEntry = post.toApi();
+  delete apiEntry.content;
+  return apiEntry;
+}
+
 /*
- * This function generates paged api index on path `/api/posts`
+ * This function generates api index on path `/api/posts`
  */
 function generateApiIndex(posts: Array<Post>, path: string) {
-  const parsedPosts = posts.map((post) => {
-    const apiEntry = post.toApi();
-    delete apiEntry.content;
-    return apiEntry;
-  });
+  const parsedPosts = posts.map(parsePosts);
   const filePath = `${path}/api/posts.json`;
   fs.writeFile(filePath, JSON.stringify(parsedPosts), (err) =>
     err ? console.log(err) : null
   );
 }
 
+/*
+ * This function generates pages on path `/api/page/<number>`
+ */
+function generatePages(posts: Array<Post>, path: string, len: number = 8) {
+  const parsedPosts = posts.map(parsePosts);
+  const pages = chunk(posts, len);
+  mkDirByPathSync(`${path}/api/page`);
+  pages.forEach((posts: Array<Post>, index: number) => {
+    const pageNumber = index + 1;
+    const page = { posts, next : pageNumber + 1 };
+    if (pageNumber == pages.length) {
+      delete page.next;
+    }
+    fs.writeFile(`${path}/api/page/${pageNumber}.json`, JSON.stringify(page), (err) =>
+                 err ? console.log(err) : null
+                );
+  })
+}
+
+
+
+
 function generateCategories(posts: Array<Post>, path: string) {
   const categories: PlainObject = {};
   posts.forEach((post) => {
@@ -92,6 +123,7 @@ export function generateApi(posts: Array<Post>, path: string) {
   try {
     generateApiIndex(posts, path);
     generateCategories(posts, path);
+    generatePages(posts, path);
     posts.forEach((post) => saveApiEntry(post, path));
   } catch (err) {
     console.log(err);