gulp-server-io
Version:
A local static server, plus livereload and a socket.io debugger for your SPA development with gulp
99 lines (86 loc) • 2.95 kB
JavaScript
/**
* This is the top level call for the underlying connect server
* The main export module will wrap that in stream
* This way, we have two different ways to use this module
*/
const _ = require('lodash');
const chalk = require('chalk');
const { serveStatic, logutil } = require('./src/lib/utils/helper');
const appGenerator = require('./src/lib/app');
const { webserver, socketServer } = require('./src/lib/server');
const debuggerServer = require('./src/lib/debugger');
const serverReload = require('./src/lib/reload/server-reload');
const reload = require('./src/lib/reload');
const debug = require('debug')('gulp-server-io:server');
const disable = {
open: false,
reload: false,
debugger: false,
development: false
};
// Export
module.exports = function(options = {}) {
let server = {};
let io = null;
let unwatchFn = [];
// We always overwrite it here to disable feature that shouldn't be use
if (!options.development) {
options = _.merge(options, disable);
}
// Generate the app
const { app, config, mockServerInstance } = appGenerator(options);
debug('server options', options);
// Static serving
app.use(config.path, serveStatic(config.webroot, config));
const cb = config.callback;
config.callback = () => {
// For some reason the config is undefined and nothing can pass to it
if (typeof cb === 'function') {
Reflect.apply(cb, null, [config]);
}
// Notify
logutil(
chalk.white(`gulp-server-io (${config.version}) running at`),
chalk.cyan(
['http', config.https ? 's' : '', '://', config.host, ':', config.port].join('')
)
);
};
// Configure the server
server = webserver(app, config);
// The socket server is delegate here to start @TODO
if (
config.reload.enable ||
(config.debugger.enable && config.debugger.server === true)
) {
io = socketServer(server, config);
}
// @TODO we need to combine the two socket server into one
// 1. check if those modules that require a socket server is needed
// 2. generate a socket server, then passing the instance back to
// their respective constructors
// Run the watcher, return an unwatch function
if (config.reload.enable) {
// Limiting the config options
unwatchFn.push(reload([config.webroot], io, config.reload));
}
// Debugger server start
if (config.debugger.enable && config.debugger.server === true) {
unwatchFn.push(debuggerServer(config, io));
}
// @TODO add watching server side files
// New @1.4.0-beta.11 watch a different path and pass a callback
if (config.serverReload.enable) {
unwatchFn.push(serverReload(config.serverReload));
}
server.on('close', () => {
mockServerInstance.close();
if (io && io.server && io.server.close) {
// Close the socket.io server
io.server.close();
}
unwatchFn.forEach(fn => fn());
});
// Return the server instance
return server;
};