Skip to content

Instantly share code, notes, and snippets.

@dylants
Last active August 29, 2015 14:00
Show Gist options
  • Save dylants/11385153 to your computer and use it in GitHub Desktop.
Save dylants/11385153 to your computer and use it in GitHub Desktop.
Hapi basic configuration
// --------------------------------------------
// --------------- app.js -------------------
// --------------------------------------------
"use strict";
var Hapi = require("hapi"),
yaml = require("js-yaml"),
fs = require("fs");
var config, serverOptions, serverConfiguration, server;
// load the configuration
config = yaml.safeLoad(fs.readFileSync("./config.yaml", "utf8"));
// hapi server options
serverOptions = {
host: process.env.HOST || config.server.host,
port: process.env.PORT || config.server.port
};
// hapi server configuration options
serverConfiguration = {
cors: true,
security: true,
views: {
engines: {
"html": "handlebars"
},
path: __dirname + "/views",
}
};
// create the hapi server
server = new Hapi.Server(serverOptions.host, serverOptions.port, serverConfiguration);
// include the routes
server.route(require("./routes").endpoints);
// start the server
server.start(function() {
console.log("Server started at: " + server.info.uri);
});
// --------------------------------------------
// ----------- routes/index.js ----------------
// --------------------------------------------
"use strict";
var memberLookup = require("./member-lookup"),
membersProxy = require("./members-proxy");
module.exports.endpoints = [
{ method: "GET", path: "/api/member-lookup/{email}", config: memberLookup.lookup },
{ method: "*", path: "/api/members/{p*}", config: membersProxy.proxy },
// Web App
{ method: "GET", path: "/app/{path*}", handler: {
view: {
template: "index.html"
}
}},
// Redirect / to the web app
{ method: "GET", path: "/", handler: function(request, reply) {
reply().redirect("/app");
}},
// static resources for web app
{ method: "GET", path: "/public/{path*}", handler: {
directory: { path: './public', listing: false, index: true }
}}
];
// --------------------------------------------
// ------- routes/member-lookup.js ------------
// --------------------------------------------
"use strict";
var Hapi = require("hapi");
module.exports.lookup = {
handler: function(request, reply) {
// grab request params
var email = request.params.email;
// do work...
if (err) {
console.error(err);
reply(Hapi.error.badImplementation(err));
return;
}
reply("done!");
}
};
// --------------------------------------------
// ------- routes/members-proxy.js ------------
// --------------------------------------------
"use strict";
function mapUri(request, callback) {
var uri;
uri = "http://proxy.com:3000/api/members/" +
request.params.p;
return callback(null, uri);
}
module.exports.proxy = {
handler: {
proxy: {
mapUri: mapUri,
passThrough: true
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment