Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var http = require("http"),
redis = require("redis");
var redisClient = redis.createClient(6379, "127.0.0.1", {});
var TTL = 300;
var server = http.createServer(function(request, response) {
var headers = {"Content-Type": "text/plain"};
if (request.method.toUpperCase() !== "POST") {
response.writeHead(405, headers);
response.end("Only POST requests are allowed!");
} else {
processBody(request, function(err, body) {
if (err != null) {
response.writeHead(err.code, headers);
response.end(err.msg);
} else {
redisClient.set(JSON.stringify(body), "1", "NX", "EX", TTL, function(err, reply) {
var status = 500;
if (err === null) {
if (reply === null) {
status = 200;
} else if (reply === "OK") {
status = 201;
}
}
response.writeHead(status, headers);
response.end();
});
}
});
}
}).listen(9000);
function processBody(request, callback) {
var strBody = "";
request.on("data", function(data) {
strBody += data;
if(strBody.length > 1e6)
callback({code: 413, msg: "Too much data."});
});
request.on("end", function() {
try {
var body = JSON.parse(strBody);
callback(null, body);
} catch (err) {
callback({code: 400, msg: "Body is not a valid JSON object."});
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment