-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
114 lines (87 loc) · 2.95 KB
/
index.js
File metadata and controls
114 lines (87 loc) · 2.95 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const express = require("express");
const path = require("path");
const fs = require("fs");
module.exports = function() {
/**
* Find the archives in the data dir
*
* @param string dir Filepath to data directroy
* @return array Returns an array of archives (folders) inside the directory
*/
this.findArchives = (dir) => {
let archives = [];
fs.readdirSync(dir).forEach((file) => {
if (!file.includes(".")) {
archives.push(file);
}
});
return archives;
};
/**
* Find JSON files in the specified directory
*
* @param string dir Filepath to directory
* @return array Returns an array of files (.json) inside the directory
*/
this.findFiles = (dir) => {
let files = [];
fs.readdirSync(dir).forEach((file) => {
if (file.includes(".json")) {
files.push(file);
}
});
return files;
};
/**
* Return the JSON contents of a file, if it exists
*
* @param string filename Filename to read
* @return mixed Returns the file JSON content or false if it's not found.
*/
this.readFile = (filename) => {
let file = false;
filename = path.normalize(process.cwd() + '/' + filename);
if (fs.existsSync(filename)) {
file = require(filename);
}
return file;
}
/**
* Create a router for each directory
*
* @param string dir Filepath to data directory
* @return array Returns an array of routers
*/
this.createRouters = (dir, data = {}) => {
// Load the dirs
let archives = this.findArchives(dir);
// Create a router for each
let routers = [];
archives.forEach(archive => {
let router = express.Router();
let archiveData = data;
let archivePath = dir + '/' + archive + '/';
let archiveView = archive + "-archive";
let singleView = archive + "-single";
archiveData.posts = this.findFiles(archivePath);
archiveData.posts = archiveData.posts.map(post => {
return this.readFile(archivePath + post);
});
router.get("/", (request, response, next) => {
console.log("data:", archiveData);
response.render(archive + "-archive", archiveData);
});
router.get("/:id", (request, response, next) => {
let singlePath = dir + '/' + archive + '/' + request.params.id +
'.json';
let singleData = data;
singleData.post = this.readFile(singlePath);
response.render(singleView, singleData);
});
// Name the router
router.archiveName = '/' + archive;
routers.push(router);
});
return routers;
}
};