Created
May 8, 2014 20:17
-
-
Save RichardLitt/2f7787557a023fa08881 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Hapi = require("hapi"); | |
var Joi = require("joi"); | |
var server = new Hapi.Server(8080, "localhost", { | |
cache: { | |
engine: "catbox-redis", | |
options: { | |
host: "localhost", | |
port: 8080, | |
partition: "MyApp", | |
password: "mypassword" | |
} | |
} | |
}); | |
server.method("getColour", function(name, next) { | |
var colours = ["red", "blue", "indigo", "violet", "green"]; | |
var colour = colours[Math.floor(Math.random() * colours.length)]; | |
next(null, colour); | |
}, { | |
cache: { | |
expiresIn: 30000, | |
} | |
}); | |
server.route({ | |
path: "/", | |
method: "GET", | |
handler: function(request, reply) { | |
reply("Hello, world!"); | |
} | |
}); | |
var helloConfig = { | |
handler: function(request, reply) { | |
var names = request.params.name.split("/"); | |
server.methods.getColour(request.params.name, function(err, colour) { | |
reply({ | |
first: names[0], | |
last: names[1], | |
mood: request.query.mood, | |
age: request.query.age, | |
colour: colour | |
}); | |
}); | |
}, | |
validate: { | |
path: { | |
name: Joi.string().min(8).max(100) | |
}, | |
query: { | |
mood: Joi.string().valid(["neutral", "happy", "sad"]).default("neutral"), | |
age: Joi.number().integer().min(13).max(100).default('25') | |
} | |
} | |
}; | |
server.route({ | |
path: "/hello/{name*2}", | |
method: "GET", | |
config: helloConfig | |
}); | |
server.start(function(){ | |
console.log("Hapi server started @ " + server.info.uri); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
{
"name": "MyApp",
"version": "0.0.1",
"description": "An example Hapi application",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"author": "Richard Littauer",
"license": "BSD",
"dependencies": {
"hapi": "~4.1.0",
"joi": "~3.1.0",
"catbox-redis": "~1.0.1"
}
}