# Code coverage report for thinkjs/lib/Lib/Util/Cookie.js

## Statements: 100% (33 / 33) Branches: 100% (22 / 22) Functions: 100% (3 / 3) Lines: 100% (33 / 33) Ignored: none

All files » thinkjs/lib/Lib/Util/ » Cookie.js

    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

    2

    82
    82
    112
    112
    69

    43
    43
    43
    2

    43
    42
    42

    3

    82

    16
    16
    16
    1

    16
    3

    16
    6

    16
    16
    2
    1

    2

    16
    1

    16
    1

    16

     /**
     * cookie操作
     * @type {Object}
     */
    module.exports = {
      /**
       * 解析
       * @param  {[type]} str [description]
       * @return {[type]}     [description]
       */
      parse: function(str){
        'use strict';
        var data = {};
        str.split(/; */).forEach(function(item) {
          var pos = item.indexOf('=');
          if (pos === -1) {
            return;
          }
          var key = item.substr(0, pos).trim();
          var val = item.substr(pos + 1).trim();
          if ('"' === val[0]) {
            val = val.slice(1, -1);
          }
          // only assign once
          if (undefined === data[key]) {
            try {
              data[key] = decodeURIComponent(val);
            } catch (e) {
              data[key] = val;
            }
          }
        });
        return data;
      },
      /**
       * 格式化
       * @param  {[type]} name    [description]
       * @param  {[type]} val     [description]
       * @param  {[type]} options [description]
       * @return {[type]}         [description]
       */
      stringify: function(name, value, options){
        'use strict';
        options = options || {};
        var item = [name + '=' + encodeURIComponent(value)];
        if (options.maxage) {
          item.push('Max-Age=' + options.maxage);
        }
        if (options.domain) {
          item.push('Domain=' + options.domain);
        }
        if (options.path) {
          item.push('Path=' + options.path);
        }
        var expires = options.expires;
        if (expires){
          if (!isDate(expires)) {
            expires = new Date(expires);
          }
          item.push('Expires=' + expires.toUTCString());
        }
        if (options.httponly) {
          item.push('HttpOnly');
        }
        if (options.secure) {
          item.push('Secure');
        }
        return item.join('; ');
      }
    }