summaryrefslogtreecommitdiffstats
path: root/mojo/public/js/bindings/connection.js
blob: 01e33e95cd25743accd0719a5088819e61ef1fcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

define("mojo/public/js/bindings/connection", [
  "mojo/public/js/bindings/connector",
  "mojo/public/js/bindings/router",
], function(connector, router) {

  function Connection(
      handle, localFactory, remoteFactory, routerFactory, connectorFactory) {
    if (routerFactory === undefined)
      routerFactory = router.Router;
    this.router_ = new routerFactory(handle, connectorFactory);
    this.remote = new remoteFactory(this.router_);
    this.local = new localFactory(this.remote);
    this.router_.setIncomingReceiver(this.local);

    // Validate incoming messages: remote responses and local requests.
    var validateRequest = localFactory.prototype.validator;
    var validateResponse = remoteFactory.prototype.validator;
    var payloadValidators = [];
    if (validateRequest)
      payloadValidators.push(validateRequest);
    if (validateResponse)
      payloadValidators.push(validateResponse);
    this.router_.setPayloadValidators(payloadValidators);
  }

  Connection.prototype.close = function() {
    this.router_.close();
    this.router_ = null;
    this.local = null;
    this.remote = null;
  };

  Connection.prototype.encounteredError = function() {
    return this.router_.encounteredError();
  };

  // The TestConnection subclass is only intended to be used in unit tests.

  function TestConnection(handle, localFactory, remoteFactory) {
    Connection.call(this,
                    handle,
                    localFactory,
                    remoteFactory,
                    router.TestRouter,
                    connector.TestConnector);
  }

  TestConnection.prototype = Object.create(Connection.prototype);

  var exports = {};
  exports.Connection = Connection;
  exports.TestConnection = TestConnection;
  return exports;
});