Created
November 29, 2013 21:05
-
-
Save Raynos/7711991 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 http = require("http") | |
var console = require("console") | |
var url = require("url") | |
var Router = require("routes-router") | |
var jsonBody = require("body/json") | |
var sendText = require("send-data") | |
var Validator = require("validate-form") | |
var app = Router() | |
var usersSchema = { | |
title: Validator.type(String), | |
status: Validator.memberOf(["open", "pending", "close"]), | |
participants: Validator.list({ | |
// not implemented or yet >_>; | |
content: Validator.or([Joi.string(), Joi.number()]) | |
}) | |
} | |
app.addRoute("/", validateQuery({ | |
username: Validator.type(String) | |
}, sendSuccess)) | |
app.addRoute("/admin", validateQuery({ | |
username: Validator.type(String), | |
password: Validator.type(String) | |
}, sendSuccess)) | |
app.addRoute("/users", validateQuery({ | |
email: [Validator.min(18), Validator.isEmail()] | |
}, sendSuccess)) | |
app.addRoute("/config", validateQuery({ | |
// I'm not sure whether list works with empty content | |
choices: Validator.list() | |
}, sendSuccess)) | |
app.addRoute("/test", validateQuery({ | |
num: [Validator.min(0), Validator.type(Number)] | |
}, sendSuccess)) | |
app.addRoute("/test2", validateQuery({ | |
itemId: Validator.type(String) | |
}, sendSuccess)) | |
app.addRoute("/simple", validateQuery({ | |
input: [Validator.type(String), Validator.min(3)] | |
}, sendSuccess)) | |
app.addRoute("/users/{id}", { "POST": userId }) | |
http.createServer(app).listen("3000", function () { | |
console.log("Listening on port 3000") | |
}) | |
function validateQuery(schema, routeHandler) { | |
return function (req, res, opts, cb) { | |
var queryObject = url.parse(req.url, true).query | |
var err = Joi.validate(queryObject, schema) | |
if (err){ | |
return cb(err._errors) | |
} | |
// We can choose to pass the query object along so that we don't | |
// have to compute it again | |
opts.query = queryObject | |
routeHandler(req, res, opts, cb) | |
} | |
} | |
function userId(req, res, opts, cb) { | |
jsonBody(req, res, function (err, body) { | |
if (err) { | |
return cb(err) | |
} | |
var errors = Joi.validate(body, usersSchema) | |
if (errors) { | |
return cb(errors._errors) | |
} | |
sendSuccess(req, res) | |
}) | |
} | |
function sendSuccess(req, res) { | |
sendText(req, res, "Success!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment