Skip to content

Instantly share code, notes, and snippets.

@rlivsey
Created March 3, 2014 23:52
Show Gist options
  • Save rlivsey/9337225 to your computer and use it in GitHub Desktop.
Save rlivsey/9337225 to your computer and use it in GitHub Desktop.
Quick hacky modification to broccoli server to work with history API
var broccoli = require('broccoli')
var helpers = require('broccoli/lib/helpers')
var path = require('path')
var hapi = require('hapi')
var synchronized = require('synchronized')
var tree = helpers.loadBrocfile()
var builder = new broccoli.Builder(tree)
serve(builder)
function serve (builder) {
console.log('Serving on http://0.0.0.0:4200/\n')
var buildError = null
var outputTmpDir = null
var server = hapi.createServer('0.0.0.0', 4200, {
views: {
engines: {
html: 'handlebars'
},
path: path.join(__dirname, '../templates')
},
state: {
cookies: {
// If we ever need to parse cookies, be sure to set
// failAction/strictHeader to be tolerant
parse: false
}
}
})
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: function (request) {
if (!outputTmpDir) throw new Error('Expected outputTmpDir to be set')
if (buildError) throw new Error('Did not expect buildError to be set')
return outputTmpDir
}
}
}
})
server.ext('onRequest', function (request, reply) {
// `synchronized` delays serving until we've finished building
synchronized(builder, function (done) {
if (buildError) {
var context = {
message: buildError.message,
file: buildError.file,
line: buildError.line,
column: buildError.column,
stack: buildError.stack
}
reply.view('error', context).code(500)
} else if (!outputTmpDir) {
// Could happen if we get a request in before the first build starts
reply('Error: No build output found').type('text/plain').code(500)
} else {
// if it's a non-asset URL then assume it's a history API URL
if (!path.extname(request.path)) {
request.setUrl("/")
}
reply() // good to go
}
done() // release lock immediately
})
})
// We register these so the 'exit' handler removing temp dirs is called
process.on('SIGINT', function () {
process.exit(1)
})
process.on('SIGTERM', function () {
process.exit(1)
})
var statsHash = null
function checkForUpdates () {
var newStatsHash = builder.treesRead.map(function (tree) {
return tree.statsHash != null ? tree.statsHash() : ''
}).join('\x00')
if (newStatsHash !== statsHash) {
statsHash = newStatsHash
builder.build()
.then(function (dir) {
outputTmpDir = dir
buildError = null
console.log('Built')
}, function (err) {
outputTmpDir = null
buildError = err
console.log('Built with error:')
// Should also show file and line/col if present; see cli.js
console.log(err.stack)
console.log('')
})
}
setTimeout(checkForUpdates, 100)
}
checkForUpdates()
server.start()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment