Last active
December 22, 2017 07:32
-
-
Save dasniko/48d65bddb06ad6eaad24 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"), | |
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