UNPKG

2.35 kBJavaScriptView Raw
1/**
2 * Kettle support for websockets/ws WebSockets-based I/O
3 *
4 * Copyright 2013 OCAD University
5 * Copyright 2015 Raising the Floor (International)
6 *
7 * Licensed under the New BSD license. You may not use this file except in
8 * compliance with this License.
9 *
10 * You may obtain a copy of the License at
11 * https://github.com/fluid-project/kettle/blob/master/LICENSE.txt
12 */
13
14"use strict";
15
16var fluid = require("infusion"),
17 kettle = fluid.registerNamespace("kettle");
18
19fluid.require("ws", require, "kettle.npm.ws");
20
21/**
22 * A grade that can be applied to the kettle.server component that extends
23 * its capabilities to support WebSockets based requests
24 */
25fluid.defaults("kettle.server.ws", {
26 members: {
27 wsServer: "@expand:kettle.server.ws.create({that}, {that}.dispatcher, {that}.options.wsServerOptions, {that}.httpServer)"
28 },
29 wsServerOptions: {
30 disableHixie: true
31 },
32 listeners: {
33 "onStopped.shredWs": "kettle.server.ws.shred({that})"
34 }
35});
36
37// Construct a fake "response" object for the purpose of fooling the session middleware into
38// executing, which would be expecting to return a cookie header for a standard HTTP request
39kettle.server.ws.fakeResponse = function () {
40 return {};
41};
42
43kettle.server.ws.create = function (server, dispatcher, wsServerOptions, httpServer) {
44 fluid.log("Initializing the ws server");
45 var options = fluid.extend({
46 server: httpServer,
47 // The entirety of the standard express middleware chain is packed into our "verifyClient" handler, that will reject handshake if any reject
48 // https://github.com/websockets/ws/blob/master/doc/ws.md#optionsverifyclient
49 verifyClient: function (info, callback) {
50 dispatcher(info.req, kettle.server.ws.fakeResponse(), callback, {expectedRequestGrade: "kettle.request.ws"});
51 }
52 }, wsServerOptions);
53 var wsServer = new kettle.npm.ws.Server(options);
54 wsServer.on("connection", function (ws, req) {
55 var request = req.fluidRequest;
56 fluid.log("Received WebSockets connection on path ", req.url);
57 request.ws = ws;
58 kettle.withRequest(request, function () {
59 request.events.onBindWs.fire(request, ws);
60 })();
61 });
62 return wsServer;
63};
64
65kettle.server.ws.shred = function (that) {
66 delete that.ws;
67};