UNPKG

2.58 kBJavaScriptView Raw
1/* eslint-disable no-console */
2var Logger = require('happn-logger'),
3 Services = require('./services/manager'),
4 util = require('../lib/services/utils/shared');
5
6module.exports = {
7 initialize: function(config, done) {
8 console.warn(
9 'use of initialize when creating happn service is deprecated. use happn.service.create'
10 );
11 return this.create(config, done);
12 },
13
14 create: util.maybePromisify(function(config, done) {
15 if (typeof config === 'function') {
16 done = config;
17 config = {};
18 }
19
20 if (!config.Logger && !Logger.configured) Logger.configure(config.utils);
21 if (config.port == null) config.port = 55000;
22 if (config.host == null) config.host = '0.0.0.0';
23
24 var happn = {
25 services: {},
26 config: config,
27 connections: {},
28 __initialized: false
29 };
30
31 var log = (config.Logger || Logger).createLogger('HappnServer');
32 log.context = happn.config.name;
33
34 happn.log = log;
35
36 happn.services = new Services();
37
38 happn.stop = util.maybePromisify(function(options, stopCB) {
39 if (!happn.__initialized)
40 log.warn('not initialized yet, trying to stop services nevertheless');
41
42 log.$$DEBUG('stopping happn');
43
44 if (typeof options === 'function') {
45 stopCB = options;
46 options = {};
47 }
48
49 return happn.services.stop(options, e => {
50 if (e) return stopCB(e); // not stopping network
51 log.$$DEBUG('stopped services');
52 return stopCB();
53 });
54 });
55
56 happn.listen = function(host, port, options, listenCB) {
57 if (typeof options === 'function') {
58 listenCB = options;
59 options = null;
60 }
61
62 if (typeof port === 'function') {
63 listenCB = port;
64 port = null;
65 options = null;
66 }
67
68 if (typeof host === 'function') {
69 listenCB = host;
70 host = null;
71 options = null;
72 }
73
74 if (!host) host = happn.config.host;
75 if (!port) port = happn.config.port;
76
77 if (!happn.__initialized) return listenCB(new Error('not initialized yet'));
78 return happn.services.transport.listen(host, port, options, listenCB);
79 };
80
81 happn.services.initialize(config, happn, function(e) {
82 if (e) {
83 console.log('Failed to initialize services', e);
84 return done(e);
85 }
86
87 happn.__initialized = true;
88 if (!config.deferListen) happn.listen(happn.config.host, happn.config.port, done);
89 else done(null, happn);
90 });
91 })
92};