-
Notifications
You must be signed in to change notification settings - Fork 6
/
import.js
85 lines (68 loc) · 1.92 KB
/
import.js
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
const fs = require(`fs`).promises;
const mysql = require(`mysql`);
const path = require(`path`);
const striptags = require(`striptags`);
const yaml = require(`js-yaml`);
const connection = mysql.createConnection({
host: `localhost`,
port: 3307,
user: `brooklynrail`,
password: `devpass`,
database: `brooklynrail`
});
const sql = `
SELECT * FROM articles
INNER JOIN issues
ON articles.issue_id = issues.id
INNER JOIN sections
ON articles.section_id = sections.id
WHERE issues.published = 1
`;
const createIssuePath = issue => {
// two-digit
const month = issue.month.toString().padStart(2, `0`);
return path
.join(__dirname, `content`, issue.year.toString(), month)
.toLowerCase();
};
const createSectionPath = result => {
const { issues: issue, sections: section } = result;
const issuePath = createIssuePath(issue);
return path.join(issuePath, section.permalink).toLowerCase();
};
const createArticlePath = result => {
const sectionPath = createSectionPath(result);
const { articles: article } = result;
const fileName = `${article.permalink}.html`;
return path.join(sectionPath, fileName).toLowerCase();
};
const getFrontmatter = article => {
const title = striptags(article.title);
return yaml.dump({
title
});
};
const createArticle = result => {
const { articles: article } = result;
const frontmatter = getFrontmatter(article);
const fileContent = `---
${frontmatter}---
${article.body}
`;
const articlePath = createArticlePath(result);
console.log(articlePath);
return fs.writeFile(articlePath, fileContent);
};
const handleResult = result => {
const sectionPath = createSectionPath(result);
fs.mkdir(sectionPath, { recursive: true })
.then(() => createArticle(result))
.catch(err => {
throw err;
});
};
connection.query({ sql, nestTables: true }, (error, results) => {
if (error) throw error;
results.forEach(handleResult);
connection.end();
});