UNPKG

sepro

Version:

Sepro is a http proxy which discovers where to proxy a request.

127 lines (102 loc) 3.08 kB
var SeaportRouter = require('./seaport') , path = require('path') , st = require('st') , inherits = require('util').inherits , EventEmitter = require('events').EventEmitter , getKey = require('../utils').getKey module.exports = SeaportStatic function SeaportStatic(options) { if (!(this instanceof SeaportStatic)) return new SeaportStatic(options) EventEmitter.call(this) options = options || {} this.cwd = options.cwd || process.cwd() this.cache = options.cache this.index = options.index || false this.dot = options.dot || false this.serverName = options.serverName || null this.routes = {} var ports = options.ports if (!ports) throw new Error('Missing seaport connection (options.ports) in SeaportStatic options') // Setup seaport ports.on('free', this.free.bind(this)) ports.on('register', this.register.bind(this)) ports.query().forEach(this.register, this) } inherits(SeaportStatic, EventEmitter) SeaportStatic.prototype.getServerNames = SeaportRouter.prototype.getServerNames SeaportStatic.prototype.register = function (service) { var paths = service.static if (!paths) return if (typeof paths === 'string') { try { paths = JSON.parse(paths) } catch (err) { paths = [ paths ] } } if (typeof paths !== 'object') return var serverNames = this.getServerNames(service) , i , j , dir , urls = [] , mount , sn if (!Array.isArray(paths)) { i = Object.keys(paths) urls = i.map(function (p) { return paths[p] }) paths = i } for (i = 0; i < paths.length; i++) { dir = path.resolve(this.cwd, paths[i]) mount = st( { path: paths[i] , url: urls[i] || '/' , cache: this.cache , index: this.index , dot: this.dot , passthrough: true } ) // Use the same cache objects for all mounts mount.cache = this._cache || (this._cache = mount.cache) mount.service = service for (j = 0; j < serverNames.length; j++) { sn = serverNames[j] if (!this.routes[sn]) this.routes[sn] = [] this.routes[sn].push(mount) } } } SeaportStatic.prototype.free = function (service) { var key = getKey(service) this.getServerNames(service).forEach(function (serverName) { if (!this.routes[serverName]) return this.routes[serverName] = this.routes[serverName].filter(function (mount) { return (getKey(mount.service) !== key) }) if (!this.routes[serverName].length) { delete this.routes[serverName] } }, this) } SeaportStatic.prototype.getMounts = function (req, target) { if (!req) return false target = target || (req.headers.host || '').split(':')[0] return this.routes[target] } SeaportStatic.prototype.handle = SeaportStatic.prototype.handleRequest = function (req, res, out) { var mounts = this.getMounts(req) if (!mounts) return out() var i = 0 ; // JSHint (function next(err) { if (err) return out(err) var mount = mounts[i++] if (!mount) return out() mount(req, res, next) }()) }