insomnia/app/backend/cookies.js

64 lines
1.3 KiB
JavaScript
Raw Normal View History

import {CookieJar} from 'tough-cookie';
/**
* Get a list of cookie objects from a request.jar()
*
* @param jar
*/
export function cookiesFromJar (jar) {
return new Promise(resolve => {
2016-10-05 04:43:48 +00:00
jar.store.getAllCookies((err, cookies) => {
if (err) {
console.warn('Failed to get cookies form jar', err);
resolve([]);
} else {
resolve(cookies);
}
});
});
}
2016-10-05 04:43:48 +00:00
/**
* Get cookies header
* @param jar
* @param uri
* @returns {Promise}
*/
export function cookieHeaderValueForUri (jar, uri) {
return new Promise((resolve, reject) => {
jar.getCookies(uri, (err, cookies) => {
if (err) {
reject(err)
} else {
resolve(cookies.join('; '));
}
})
})
}
/**
* Get a request.jar() from a list of cookie objects
*
* @param cookies
*/
export function jarFromCookies (cookies) {
try {
2016-10-05 04:43:48 +00:00
return CookieJar.fromJSON({cookies});
} catch (e) {
console.log('Failed to initialize cookie jar', e);
2016-10-05 04:43:48 +00:00
return new CookieJar();
}
}
export function cookieToString (cookie) {
var str = cookie.toString();
// tough-cookie toString() doesn't put domain on all the time.
// This hack adds when tough-cookie won't
if (cookie.domain && cookie.hostOnly) {
str += '; Domain=' + cookie.domain;
}
return str;
}