forked from carbon-design-system/carbon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
103 lines (90 loc) · 2.6 KB
/
server.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
101
102
103
'use strict';
const globby = require('globby');
const Promise = require('bluebird');
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const adaro = require('adaro');
const port = process.env.PORT || 8080;
const htmlFiles = {
// Used in getContent() function
all: [
'src/components/**/*.html',
'!src/components/unified-header/*.html',
'!src/components/inline-left-nav/*.html',
],
};
const directoryOrder = [
// Used for allLinks() function
'src/components/**/*.html',
];
app.engine('dust', adaro.dust());
app.set('view engine', 'dust');
app.set('views', path.resolve(__dirname, 'demo/views'));
app.use(express.static('node_modules'));
app.use(express.static('demo'));
app.use(express.static('src'));
app.use('/docs/js', express.static('docs/js'));
const getContent = glob =>
globby(glob)
.then((paths) => { // eslint-disable-line arrow-body-style
return paths.length === 0 ? undefined : paths
.map(file => fs.readFileSync(file, { encoding: 'utf8' }))
.reduce((a, b) => a.concat(b));
});
const allLinks = globby(directoryOrder)
.then((paths) => { // eslint-disable-line arrow-body-style
return paths
.map((filePath) => {
const indices = [];
for (let i = 0; i < filePath.length; i++) {
if (filePath[i] === '/') {
indices.push(i);
}
}
return filePath.slice(0, indices[1]);
})
.filter((filePath, index, a) => a.indexOf(filePath) === index)
.map(filePath => ({
url: filePath,
}));
});
app.get('/', (req, res) => {
Promise.all([
getContent(htmlFiles.all),
])
.then((results) => {
res.render('demo-all', {
html: results[0],
});
})
.catch((error) => {
console.error(error.stack); // eslint-disable-line no-console
res.status(500).end();
});
});
app.get('/components/:component', (req, res) => {
const glob = `src/components/${req.params.component}/**/*.html`;
if (path.relative('src/components', glob).substr(0, 2) === '..') {
res.status(404).end();
} else {
Promise.all([getContent(glob), allLinks])
.then((results) => {
if (typeof results[0] === 'undefined') {
res.status(404).end();
} else {
res.render('demo-all', {
html: results[0],
});
}
})
.catch((error) => {
console.error(error.stack); // eslint-disable-line no-console
res.status(500).end();
});
}
});
app.listen(port, () => {
console.log(`Listening on port: ${port}`); // eslint-disable-line no-console
});