« index

Coverage for /Users/kris/q-io/http-cookie.js : 79%

73 lines | 58 run | 15 missing | 0 partial | 16 blocks | 5 blocks run | 11 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

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

  /**
   * Provides utilities for reading and writing HTTP cookies.
   * @module
   */
  
  /*whatsupdoc*/
  
  var QS = require("qs");
  
  /**
   * @param {String} cookie
   * @returns {Object}
   */
  exports.parse = function (cookie, date) {
      date = date || new Date();
      var parsed = {};
      var terms = cookie.split(/[;,]/g);
      var keyValue = terms.shift().split("=");
      parsed.key = keyValue[0];
      parsed.value = keyValue[1];
      terms.forEach(function (term) {
          var parts = term.split("=").map(function (part) {
              return part.trim();
          });
          var key = parts[0], value = parts[1];
          if (/^domain$/i.test(key)) {
              parsed.domain = value;
          } else if (/^path$/i.test(key)) {
              parsed.path = value;
          } else if (/^expires$/i.test(key)) {
              parsed.expires = new Date(
                  +new Date() + // actual now
                  (new Date(value) - date) // server offset
              );
          } else if (/^max-age$/i.test(key)) {
              parsed.expires = new Date(
                  new Date().getTime() +
                  (value * 1000)
              );
          } else if (/^secure$/i.test(key)) {
              parsed.secure = true;
          } else if (/^httponly$/i.test(key)) {
              parsed.httpOnly = true;
          }
      });
      return parsed;
  };
  
  /**
   * @param {String} key
   * @param {String} value
   * @param {Object} options (optional)
   * @returns {String} a cookie string
   */
  exports.stringify = function (key, value, options) {
      var cookie = (
          encodeURIComponent(key) + "=" +
          encodeURIComponent(value)
      );
      if (options) {
          if (options.domain)
              cookie += "; Domain=" + encodeURIComponent(options.domain);
          if (options.path)
              cookie += "; Path=" + encodeURIComponent(options.path);
          if (options.expires)
              cookie += "; Expires=" + options.expires.toGMTString();
          if (options.secure)
              cookie += "; Secure";
          if (options.httpOnly)
              cookie += "; HttpOnly";
      }
      return cookie;
  };
« index | cover.io