1 | var task = require ('./base'),
|
2 | util = require ('util');
|
3 |
|
4 | var clientCookie = module.exports = function (config) {
|
5 |
|
6 | this.init (config);
|
7 |
|
8 | };
|
9 |
|
10 | util.inherits (clientCookie, task);
|
11 |
|
12 | util.extend (clientCookie.prototype, {
|
13 |
|
14 | run: function() {
|
15 |
|
16 | var self = this;
|
17 | self.failed('use method [parse|render]');
|
18 |
|
19 | },
|
20 |
|
21 |
|
22 |
|
23 | parse: function() {
|
24 |
|
25 | var self = this,
|
26 | headers = self.headers || (self.response && self.response.headers) || null,
|
27 | cookie = self.cookie || (headers && headers['set-cookie']) || '';
|
28 |
|
29 | if (cookie.constructor != Array) cookie = [cookie];
|
30 |
|
31 | if (self.hashMap) {
|
32 |
|
33 | var cookieObj = {};
|
34 |
|
35 | cookie.forEach (function(item) {
|
36 |
|
37 | item = self.deserializeCookie(item);
|
38 | cookieObj[item.name] = item;
|
39 |
|
40 | });
|
41 |
|
42 | self.completed (cookieObj);
|
43 |
|
44 | } else {
|
45 |
|
46 | var cookieArr = cookie.map (function(item) {
|
47 |
|
48 | return self.deserializeCookie(item);
|
49 |
|
50 | });
|
51 |
|
52 | self.completed (cookieArr);
|
53 |
|
54 | }
|
55 |
|
56 | },
|
57 |
|
58 | deserializeCookie: function(coockieStr) {
|
59 |
|
60 | var self = this,
|
61 | pairs = coockieStr.split('; '),
|
62 | cookie = {};
|
63 |
|
64 | var nameValue = pairs.shift().split('=');
|
65 |
|
66 | cookie.name = nameValue[0];
|
67 | cookie.value = decodeURIComponent(nameValue[1]);
|
68 |
|
69 | if (pairs.length) pairs.forEach(function(pair) {
|
70 |
|
71 | pair = pair.split('=');
|
72 |
|
73 | var key = pair.shift(),
|
74 | value = pair.join('');
|
75 |
|
76 | cookie[key] = value || true;
|
77 |
|
78 | });
|
79 |
|
80 | if (cookie.expires) cookie.expires = ~~(new Date(cookie.expires).getTime()/1000);
|
81 |
|
82 | if (!cookie.domain) cookie.domain = self.defaultDomain;
|
83 |
|
84 | return cookie;
|
85 | },
|
86 |
|
87 | render: function () {
|
88 |
|
89 | var self = this;
|
90 |
|
91 | var cookie = [];
|
92 |
|
93 | self.cookie.map(function(item) {
|
94 |
|
95 | cookie.push(item.name + '=' + encodeURIComponent(item.value));
|
96 |
|
97 | });
|
98 |
|
99 | self.completed (cookie);
|
100 | }
|
101 |
|
102 | });
|