2011-11-18 20:51:38 +00:00
|
|
|
var winston = require('winston');
|
|
|
|
|
|
|
|
// For handling serving stored documents
|
|
|
|
|
2011-11-18 21:54:16 +00:00
|
|
|
var DocumentHandler = function(options) {
|
|
|
|
this.keyLength = options.keyLength || 20;
|
2011-11-18 20:51:38 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// TODO implement with FS backend
|
|
|
|
DocumentHandler.documents = {};
|
|
|
|
|
2011-11-18 21:45:48 +00:00
|
|
|
// Handle retrieving a document
|
2011-11-18 20:51:38 +00:00
|
|
|
DocumentHandler.prototype.handleGet = function(key, response) {
|
|
|
|
if (DocumentHandler.documents[key]) {
|
|
|
|
winston.verbose('retrieved document', { key: key });
|
|
|
|
response.writeHead(200, { 'content-type': 'application/json' });
|
2011-11-18 21:42:05 +00:00
|
|
|
response.end(JSON.stringify({ data: DocumentHandler.documents[key], key: key }));
|
2011-11-18 20:51:38 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
winston.warn('document not found', { key: key });
|
2011-11-18 21:50:23 +00:00
|
|
|
response.writeHead(404, { 'content-type': 'application/json' });
|
2011-11-18 20:51:38 +00:00
|
|
|
response.end(JSON.stringify({ message: 'document not found' }));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2011-11-18 21:45:48 +00:00
|
|
|
// Handle adding a new Document
|
2011-11-18 20:51:38 +00:00
|
|
|
DocumentHandler.prototype.handlePost = function(request, response) {
|
2011-11-18 21:45:48 +00:00
|
|
|
var key = this.randomKey();
|
2011-11-18 20:51:38 +00:00
|
|
|
request.on('data', function(data) {
|
|
|
|
if (!DocumentHandler.documents[key]) {
|
2011-11-18 21:28:09 +00:00
|
|
|
response.writeHead(200, { 'content-type': 'application/json' });
|
2011-11-18 20:51:38 +00:00
|
|
|
DocumentHandler.documents[key] = '';
|
|
|
|
}
|
|
|
|
DocumentHandler.documents[key] += data.toString();
|
|
|
|
});
|
|
|
|
request.on('end', function(end) {
|
|
|
|
winston.verbose('added document', { key: key });
|
2011-11-18 21:25:18 +00:00
|
|
|
response.end(JSON.stringify({ key: key }));
|
2011-11-18 20:51:38 +00:00
|
|
|
});
|
|
|
|
request.on('error', function(error) {
|
2011-11-18 21:28:09 +00:00
|
|
|
winston.error('connection error: ' + error.message);
|
|
|
|
response.writeHead(500, { 'content-type': 'application/json' });
|
|
|
|
response.end(JSON.stringify({ message: 'connection error' }));
|
2011-11-18 20:51:38 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2011-11-18 21:45:48 +00:00
|
|
|
// Generate a random key
|
|
|
|
DocumentHandler.prototype.randomKey = function() {
|
|
|
|
var text = '';
|
|
|
|
var keyspace = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
2011-11-18 21:54:16 +00:00
|
|
|
for (var i = 0; i < this.keyLength; i++) {
|
2011-11-18 21:45:48 +00:00
|
|
|
text += keyspace.charAt(Math.floor(Math.random() * keyspace.length));
|
|
|
|
}
|
|
|
|
return text;
|
|
|
|
};
|
2011-11-18 21:22:00 +00:00
|
|
|
|
2011-11-18 20:51:38 +00:00
|
|
|
module.exports = DocumentHandler;
|