latency.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var Immutable = require("immutable");
  2. module.exports.init = function (ui, bs) {
  3. var timeout = 0;
  4. var optPath = ["remote-debug", "latency"];
  5. ui.setOptionIn(optPath, Immutable.Map({
  6. name: "latency",
  7. title: "Latency",
  8. active: false,
  9. tagline: "Simulate slower connections by throttling the response time of each request.",
  10. rate: 0
  11. }));
  12. var methods = {
  13. toggle: function (value) {
  14. if (value !== true) {
  15. value = false;
  16. }
  17. if (value) {
  18. ui.setOptionIn(optPath.concat("active"), true);
  19. bs.addMiddleware("*", function (req, res, next) {
  20. setTimeout(next, timeout);
  21. }, {id: "cp-latency", override: true});
  22. } else {
  23. ui.setOptionIn(optPath.concat("active"), false);
  24. bs.removeMiddleware("cp-latency");
  25. }
  26. },
  27. adjust: function (data) {
  28. timeout = parseFloat(data.rate) * 1000;
  29. var saved = ui.options.getIn(optPath.concat("rate"));
  30. if (saved !== data.rate) {
  31. ui.setOptionIn(optPath.concat("rate"), timeout/1000);
  32. }
  33. },
  34. event: function (event) {
  35. methods[event.event](event.data);
  36. }
  37. };
  38. return methods;
  39. };