HenningM / express-ws

WebSocket endpoints for express applications
BSD 2-Clause "Simplified" License
877 stars 142 forks source link

Example using applyTo #86

Open kirankashalkar opened 7 years ago

kirankashalkar commented 7 years ago

How does one use applyTo?

Here's my sample router module test_router.js:

var app = require('express');
var router = app.Router();
router.ws('/api/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

Here is a snippet from my main app:

// other obvious code
httpServer = http.createServer(app);
expressWs = require('express-ws')(app, httpServer, {leaveRouterUntouched: true});

var testRouter = require('test_router');
expressWs.applyTo(testRouter);

I've tried other combinations as well but obviously above code barfs on the line router.ws when requiring test_router. Is there no way to use express-ws in a router that doesn't need an instance of the app to be passed in?

bensalilijames commented 6 years ago

Just leaving this here in case it helps others:

import express from 'express';
import patch from 'express-ws/lib/add-ws-method';

patch(express.Router);

const router = express.Router();

router.ws('/route', () => { ... });

export default router;

This way, we're patching express.Router without an instance of an express application, so you can use .ws() and export the router without passing in a ws-ified app. 🙂

It's safe to do this in every file that has a router too - since add-ws-method only patches the target if it's not already been patched.