« index

Coverage for /Users/kris/q-io/http-apps/html.js : 98%

56 lines | 55 run | 1 missing | 0 partial | 10 blocks | 9 blocks run | 1 blocks missing

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

  var Q = require("q");
  // TODO negotiate text/html vs text/html+fragment (or other mime type)
  
  /**
   * @param {Request} request
   * @param {String} path
   * @param {String} contentType
   * @returns {Response}
   */
  exports.HandleHtmlFragmentResponses = function (app, handleHtmlFragmentResponse) {
      handleHtmlFragmentResponse = handleHtmlFragmentResponse || exports.handleHtmlFragmentResponse;
      return function (request) {
          request.handleHtmlFragmentResponse = handleHtmlFragmentResponse;
          return Q.fcall(app, request)
          .then(function (response) {
              if (response.htmlFragment) {
                  return Q.fcall(handleHtmlFragmentResponse, response);
              } else {
                  return response;
              }
          });
      };
  };
  
  exports.handleHtmlFragmentResponse = function (response) {
      var htmlFragment = response.htmlFragment;
      delete response.htmlFragment;
      response.headers["content-type"] = "text/html; charset=utf-8";
      response.body = {
          forEach: function (write) {
              write("<!doctype html>\n");
              write("<html>\n");
              write("    <head>\n");
              if (response.htmlTitle !== void 0) {
                  write("        <title>" + escapeHtml(response.htmlTitle) + "</title>\n");
              }
              write("    </head>\n");
              write("    <body>\n");
              htmlFragment.forEach(function (line) {
                  write("        " + line);
              });
              write("    </body>\n");
              write("</html>\n");
          }
      };
      return response;
  };
  
  exports.escapeHtml = escapeHtml;
  function escapeHtml(text) {
      return String(text)
          .replace(/&/g, "&amp;")
          .replace(/</g, "&lt;")
          .replace(/>/g, "&gt;")
          .replace(/"/g, "&quot;")
  }
« index | cover.io