Skip to content

Instantly share code, notes, and snippets.

@iissnan
Created September 21, 2016 08:05
Show Gist options
  • Save iissnan/3c5e46cb3e0bea086abce1f1ea255901 to your computer and use it in GitHub Desktop.
Save iissnan/3c5e46cb3e0bea086abce1f1ea255901 to your computer and use it in GitHub Desktop.
DPW HTML Pages Pre-process
'use strict';
const Promise = require('bluebird');
const _ = require('lodash');
const path = require('path');
const fs = require('../lib/fs');
const server = require('../server');
const config = require('../config');
server.route({
method: 'GET',
path: '/{path*}',
handler: function (request, reply) {
if (_.endsWith(request.path, '.html')) {
resolveFileIn(request, config.pages.developer)
.then(function (file) {
let filePath = config.pages.absolute(config.pages.developer, file);
includePartials(filePath, config.partials.developer)
.then(function (response) {
reply(response).type('text/html');
});
})
.catch(function () {
resolveFileIn(request, config.pages.common)
.then(function (file) {
})
.catch(function () {
reply('Not Found');
})
});
} else {
reply('not match');
}
}
});
function resolveFileIn(request, dir) {
return fs.readdir(config.pages.developer).filter(function (entry) {
const requestFile = request.path.substring(1);
return _.endsWith(entry, '.html') && entry === requestFile;
}).then(function (file) {
return new Promise(function (resolve, reject) {
file.length === 0 ? reject() : resolve(file[0]);
});
});
}
function includePartials(page, partialPath) {
let reInclude = /\{\{include ([-_.\/\w]+)}}/g;
return fs.readFile(page).then(function(pageContents) {
return replaceAsync(pageContents, reInclude, function (match, partial) {
let includeFilePath = path.join(partialPath, formatPartialName(partial));
return includePartials(includeFilePath, partialPath);
});
});
function formatPartialName(partial) {
return /.+\.html$/.test(partial) ? partial : partial + '.html';
}
}
function replaceAsync(str, re, callback) {
// http://es5.github.io/#x15.5.4.11
str = String(str);
var parts = [],
i = 0;
if (Object.prototype.toString.call(re) == "[object RegExp]") {
if (re.global)
re.lastIndex = i;
var m;
while (m = re.exec(str)) {
var args = m.concat([m.index, m.input]);
parts.push(str.slice(i, m.index), callback.apply(null, args));
i = re.lastIndex;
if (!re.global)
break; // for non-global regexes only take the first match
if (m[0].length == 0)
re.lastIndex++;
}
} else {
re = String(re);
i = str.indexOf(re);
parts.push(str.slice(0, i), callback.apply(null, [re, i, str]));
i += re.length;
}
parts.push(str.slice(i));
return Promise.all(parts).then(function(strings) {
return strings.join("");
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment