00001
00006 function Cookies() {
00007 this.cookies = {}
00008 }
00009
00010 Cookies.prototype = {
00017 get: function(name) {
00018 var cookie = this.cookies[name]
00019 if (cookie && this.checkNotExpired(name)) {
00020 return this.cookies[name].value
00021 }
00022 return null
00023 },
00024
00033 set: function(name, value, options) {
00034 var cookie = typeof options == 'object'
00035 ? {value: value, expires: options.expires, secure: options.secure || false, new: options.new || false}
00036 : {value: value}
00037 if (this.checkNotExpired(name, cookie)) {
00038 this.cookies[name] = cookie
00039 }
00040 },
00041
00042
00043 getExpirationDate: function(name) {
00044 return this.cookies[name] ? this.cookies[name].expires : null
00045 },
00046
00047
00048 checkNotExpired: function(name, cookie) {
00049 if (typeof cookie === 'undefined') {
00050 cookie = this.cookies[name]
00051 }
00052 var now = new Date()
00053 if (cookie && cookie.expires && now > cookie.expires) {
00054 delete this.cookies[name]
00055 return false
00056 }
00057 return true
00058 },
00059
00060
00066 parseResponse: function(headers) {
00067 var cookies = headers['set-cookie']
00068 if (cookies) {
00069 cookies.forEach(function(c) {
00070 var cookiesParams = c.split(';')
00071 var cookiePair = cookiesParams.shift().split('=')
00072 var options = {}
00073 cookiesParams.forEach(function(param) {
00074 param = param.trim()
00075 if (param.toLowerCase().indexOf('expires') == 0) {
00076 var date = param.split('=')[1].trim()
00077 options.expires = new Date(date)
00078 }
00079 })
00080 this.set(cookiePair[0].trim(), cookiePair[1].trim(), options)
00081 }.bind(this))
00082 }
00083 },
00084
00090 composeRequest: function(headers) {
00091 if (Object.keys(this.cookies).length == 0) {
00092 return
00093 }
00094 headers['Cookie'] = this.toString()
00095 },
00096
00097
00102 toString: function() {
00103 return Object.keys(this.cookies)
00104 .filter(this.checkNotExpired.bind(this))
00105 .map(function(name) {
00106 return name + '=' + this.cookies[name].value
00107 }.bind(this)).join(';')
00108 }
00109 }
00110
00111 module.exports = Cookies