Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created December 16, 2012 03:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Raynos/4303009 to your computer and use it in GitHub Desktop.
var url = require("url")
module.exports = rest
function rest(db) {
return function route(req, res) {
var uri = url.parse(req.url)
, paths = uri.pathname.split("/")
, length = paths.length
, key = paths[length - 1]
, method = paths[length - 2]
, action
if (method === "get") {
action = "get"
} else if (method === "put") {
action = "put"
} else if (method === "del") {
action = "del"
} else if (method === "batch") {
action = "batch"
} else if (method === "readStream") {
action = "readStream"
} else if (req.method === "GET") {
action = "get"
} else if (req.method === "POST" || req.method === "PUT") {
action = "put"
} else if (req.method === "DELETE") {
action = "del"
}
if (action === "get") {
db.get(key, returnValue)
} else if (action === "del") {
db.del(key, returnValue)
} else if (action === "readStream") {
var parts = key.split("~")
var stream = db.readStream({
start: parts[0]
, end: parts[1]
})
res.setHeader("content-type", "application/json")
stream.on("data", function (chunk) {
res.write(JSON.stringify(chunk) + "\n")
})
stream.on("end", function () {
res.end()
})
} else {
jsonBody(res, res, function (err, body) {
if (err) {
return error(req, res, err)
}
if (action === "put") {
db.put(key, body, returnValue)
} else if (action === "batch") {
db.batch(value, returnValue)
}
})
}
function returnValue(err, value) {
if (err) {
return error(req, res, err)
}
sendJson(req, res, value)
}
}
}
function jsonBody(req, res, callback) {
var result = ""
req.on("data", function (chunk) {
result += chunk
})
req.on("end", function () {
var json
try {
json = JSON.parse(result)
} catch (err) {
callback(err)
}
callbak(null, json)
})
}
function error(req, res, err) {
res.statusCode = 500
res.end(err.message)
}
function sendJson(req, res, data) {
res.setHeader("content-type", "application/json")
res.statusCode = 200
data = new Buffer(JSON.stringify(data))
res.setHeader("content-length", data.length)
res.end(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment