irrelon-reactor-autonet
Version:
A module for automatically creating groups of self-networking services.
131 lines (105 loc) • 3.11 kB
JavaScript
import express from 'express';
import bodyParser from 'body-parser';
import freeport from 'freeport';
import EventEmitter from './EventEmitter';
class Server extends EventEmitter {
constructor (name) {
super(name);
this._routes = {};
this.app = express();
// Enable JSON support
this.app.use(bodyParser.json());
// Enable url-encoding support
this.app.use(bodyParser.urlencoded({extended: true}));
// Enable pre-flight CORS
this.app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-irrelon-auth');
// Intercept OPTIONS method
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
}
start (host, port, callback) {
var self = this;
if (!port || port === 0 || port === '0' || port === undefined) {
// Get a free port first
freeport(function(err, availablePort) {
if (err) {
throw err;
}
self._start(availablePort, host, function (err, data) {
if (!err) {
//self.log('Listening at ' + host + ' on port ' + availablePort);
callback(false, self.server.address());
}
});
});
} else {
self._start(port, host, function () {
self.log('Listening at ' + host + ' on port ' + port);
callback(false);
});
}
}
_start (port, host, cb) {
this.server = this.app.listen(port, host, cb);
}
staticRoute (path, filePath) {
this.log('Service static files at ' + path + ' from ' + __dirname + filePath);
this.app.use(path, express.static(__dirname + filePath));
}
optionsRoute (path, callback) {
this._routes[path] = this._routes[path] || {
methods: [],
protocol: 'http://'
};
this._routes[path].methods.push('OPTIONS');
this.app.options(path, callback);
}
headRoute (path, callback) {
this._routes[path] = this._routes[path] || {
methods: [],
protocol: 'http://'
};
this._routes[path].methods.push('HEAD');
this.app.head(path, callback);
}
getRoute (path, callback) {
this._routes[path] = this._routes[path] || {
methods: [],
protocol: 'http://'
};
this._routes[path].methods.push('GET');
this.app.get(path, callback);
}
putRoute (path, callback) {
this._routes[path] = this._routes[path] || {
methods: [],
protocol: 'http://'
};
this._routes[path].methods.push('PUT');
this.app.put(path, callback);
}
postRoute (path, callback) {
this._routes[path] = this._routes[path] || {
methods: [],
protocol: 'http://'
};
this._routes[path].methods.push('POST');
this.app.post(path, callback);
}
deleteRoute (path, callback) {
this._routes[path] = this._routes[path] || {
methods: [],
protocol: 'http://'
};
this._routes[path].methods.push('DELETE');
this.app.delete(path, callback);
}
}
export default Server;