hapijs / nes

WebSocket adapter plugin for hapi routes
Other
502 stars 87 forks source link

Access server.publish from another file #310

Closed CarolineBoyer closed 4 years ago

CarolineBoyer commented 4 years ago

Support plan

Context

How can we help?

This might be a stupid question but I fail to see how I can use hapi/nes pub/sub with the publish being in a diffrent file from the server.start. (something like https://stackoverflow.com/questions/27766623/how-to-store-routes-in-separate-files-when-using-hapi ) but for accessing the server from a different file,

Server.js

require('dotenv').config();

const path = require('path');
const Hapi = require('@hapi/hapi');
const Nes = require('@hapi/nes');
const logger = require('../config/winston')('server');

const routes = require('./routes');
const socketRoutes = require('./api/socket/routes');
const navisRoutes = require('./api/navis/routes');

const configDev = require("../config/webpack.config.dev");
const configProd = require("../config/webpack.config.prod");

const mongoose = require('mongoose');
const initMongo = require('../config/config.mongoose');

const TrainingServiceInstance = require('./services/TrainingService')

const OpenIdService = require('./services/sso/OpenIdService');

const environment = process.env.NODE_ENV || 'production';
const isThisProduction = environment === 'production';

const serverConfigurationOptions = {
    port: process.env.SERVER_PORT,
    // host: process.env.SERVER_HOST,
    routes : {
        files: {
            relativeTo: path.join(__dirname, '../dist')
        }
    },
    debug: isThisProduction ? {} : { request: ['error'] }
};

const server = Hapi.Server(serverConfigurationOptions);

// in case Server is shut down in a meanie way.
process.on('SIGTERM', () => {
    server.log(['info', 'shutdown'], 'Graceful shutdown');
    server.stop({ timeout: Config.shutdownTimeout }).then(() => process.exit(0));
});

server.validator(require('@hapi/joi'))

exports.start = async () => {
  // first, connect to db
  await initMongo(mongoose).then(
    () => {
      logger.info("MONGOOSE CONNECTING SUCCESS")
    })
    .catch(err => logger.error("MONGOOSE CONNECTING ERROR : ", err));

    try {
        //adding link between hapi and webpack using third-party MIT plugin hapi-universal-webpack-plugin
    await server.register([{
            plugin: require('hapi-universal-webpack-plugin'),
            options: {
                clientConfig: isThisProduction ? configProd : configDev
            },
        },
        {
            plugin: require('@hapi/inert')
        }
        ]);

    } catch (errorWhenLinkingPlugin) {
        console.trace("Error when Linking one of the plugin ======= " + errorWhenLinkingPlugin)
    }

    // websocket protocol registration
    const onConnection = (socket) => {
        logger.info('Chat connected to server');
        socket.app.authToken = <TOKEN>
    };

        server.route(navisRoutes);
    await server.register({plugin: Nes, options: {onConnection, auth: false} });
    server.route(socketRoutes);
    server.subscription('/livechat/{conversationId}'); // This line allows server to prepare live exchange with SSAI Livechat using socket subscription.

    //General Routing
    server.route(routes);
    // Deal with files if they are *js *css for instance. (mandatory for the calls from the page itself)
    server.route({
        method: 'GET',
        path: '/{param*}',
        handler: {
            directory: {
                path: '.',
                redirectToSlash: true,
                index: true
            }
        }
    });
    server.route({
        method: 'GET',
        path: '/integrationChat.html',
        handler: {
            file: "./integrationChat.html"
        },
    });

    //Starting server itself
    try {
        await server.start();
        logger.info(`Server started in ${environment} mode running at : ${server.info.uri}`);
    return TrainingServiceInstance.init();
    } catch (errorWhenStartingServer) {
    logger.error(`Oh no ! Starting Server went wrong ! \n ${errorWhenStartingServer}`);
    }
};

exports.init = async () => {
  await server.initialize();
  return server;
};

exports.server = () => {
    return server;
};

the place where I would like to access to publish is in another file as I need to publish to /livechat/{conversationId} only when that module is being used by and getting data.

Basically that would be

LiveChatInitialize

return livechatApi.post({
    resourceUrl: '/startchatuser',
        data : {params}
}).then((resultFromStartingUserChat) => {
     server().publish(`/livechat/${conversation._id}`, resultFromStartingUserChat);
}
hueniverse commented 4 years ago

Unfortunately, no community resources were available to help resolve this issue after two weeks, and it is being closed. We close unresolved community issues to keep the issue tracker organized and effective. Please check https://hapi.dev/support for other support options.