-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackbit-pull.js
executable file
·100 lines (88 loc) · 2.88 KB
/
stackbit-pull.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const fs = require('fs');
const path = require('path');
const https = require('https');
const url = require('url');
const yaml = require('js-yaml');
const stackbitPullApiUrl = url.parse("https://api.stackbit.com/pull/5d0cbbbc05bd0c001584374e");
const API_KEY = process.env['STACKBIT_API_KEY'];
const data = JSON.stringify({apiKey: API_KEY});
const options = {
host: stackbitPullApiUrl.host,
path: stackbitPullApiUrl.path,
protocol: stackbitPullApiUrl.protocol,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let respdata = '';
res.on('data', chunk => {
respdata += chunk;
});
res.on('end', () => {
if (res.statusCode === 404) {
throw new Error('Project not found');
}
if (res.statusCode >= 400) {
const err = JSON.parse(respdata);
throw new Error(`Failed to build project, ${err.message}`);
}
const pages = JSON.parse(respdata);
for (let i = 0; i < pages.length; i++) {
const fullPath = path.join(__dirname, pages[i].filePath);
ensureDirectoryExistence(fullPath);
if (fs.existsSync(fullPath) && ['yml','yaml','json'].includes(path.extname(fullPath).substring(1))){
pages[i].data = mergeConfig(fullPath, pages[i].data);
}
console.log('creating file', fullPath);
fs.writeFileSync(fullPath, pages[i].data);
}
});
});
function loadLocalConfig(filepath) {
const extension = path.extname(filepath).substring(1);
let content = fs.readFileSync(filepath);
let result;
switch (extension) {
case 'yml':
case 'yaml':
result = yaml.safeLoad(content);
break;
case 'json':
result = JSON.parse(content);
break;
default:
return null
}
return result;
}
function mergeConfig(fullPath, remoteData) {
let localObj = loadLocalConfig(fullPath);
if (localObj) {
let remoteObj;
if (['yml','yaml'].includes(path.extname(fullPath).substring(1))) {
remoteObj = yaml.safeLoad(remoteData);
return yaml.safeDump(Object.assign(localObj, remoteObj));
} else {
remoteObj = JSON.parse(remoteData);
return JSON.stringify(Object.assign(localObj, remoteObj), null, 4);
}
}
return remoteData;
}
req.on('error', (e) => {
throw `Error fetching project build: ${e.message}`;
});
function ensureDirectoryExistence(filePath) {
const dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
console.log(`fetching data for project from ${stackbitPullApiUrl.href}`);
req.write(data);
req.end();