ButlerBin/server.js

90 lines
2.2 KiB
JavaScript

var Connect = require('connect');
var ConnectSt = require('st');
var Fs = require('fs');
var Http = require('http');
var Route = require('connect-route');
var Winston = require('winston');
var DocumentHandler = require('./lib/document_handler');
var KeyGenerator = require('./lib/key_generator');
var Store = require('./lib/document_store');
// Load the configuration and set some defaults
var config = JSON.parse(Fs.readFileSync('./config.js', 'utf8'));
config.host = config.host || '127.0.0.1';
config.port = config.port || 7777;
// Set up the logger
if (config.logging) {
try {
Winston.remove(Winston.transports.Console);
} catch(e) {
// This is fine
}
var detail, type;
for (var i = 0; i < config.logging.length; i++) {
detail = config.logging[i];
type = detail.type;
delete detail.type;
Winston.add(Winston.transports[type], detail);
}
}
// Configure the data store
store = new Store();
// Pick up a key generator
var keyGenerator = new KeyGenerator();
// Configure the document handler
var documentHandler = new DocumentHandler({
store: store,
maxLength: config.maxLength,
keyLength: config.keyLength,
keyGenerator: keyGenerator
});
var app = Connect();
// API
app.use(Route(function(router) {
router.get('/raw/:id', function(request, response) {
var key = request.params.id.split('.')[0];
return documentHandler.handleRawGet(key, response);
});
router.post('/documents', function(request, response) {
return documentHandler.handlePost(request, response);
});
router.get('/documents/:id', function(request, response) {
var key = request.params.id.split('.')[0];
return documentHandler.handleGet(key, response);
});
}));
// Static files
app.use(ConnectSt({
path: __dirname + '/static',
content: { maxAge: config.staticMaxAge },
passthrough: true,
index: false
}));
// All the pastebin IDs
app.use(Route(function(router) {
router.get('/:id', function(request, response, next) {
request.sturl = '/';
next();
});
}));
// Index
app.use(ConnectSt({
path: __dirname + '/static',
content: { maxAge: config.staticMaxAge },
index: 'index.html'
}));
Http.createServer(app).listen(config.port, config.host);
Winston.info('Listening on ' + config.host + ':' + config.port);