insomnia/app/common/cookies.js

77 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-10-16 22:19:16 +00:00
import {CookieJar, Cookie} 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 {
// NOTE: Perform toJSON so we have a plain JS object instead of Cookie instance
resolve(cookies.map(c => c.toJSON()));
}
});
});
}
2016-10-05 04:43:48 +00:00
/**
* Get cookies header
* @param jar
* @param uri
* @returns {Promise}
*/
export function cookieHeaderValueForUri (jar, uri) {
2016-11-10 09:00:29 +00:00
return new Promise(resolve => {
2016-10-05 04:43:48 +00:00
jar.getCookies(uri, (err, cookies) => {
2016-11-10 09:00:29 +00:00
cookies = err ? [] : cookies;
resolve(cookies.map(c => c.cookieString()).join('; '));
});
});
2016-10-05 04:43:48 +00:00
}
/**
* Get a request.jar() from a list of cookie objects
*
* @param cookies
*/
export function jarFromCookies (cookies) {
2016-10-06 16:52:26 +00:00
let jar;
try {
// For some reason, fromJSON modifies `cookies`. Create a copy first
// just to be sure
const copy = JSON.stringify({cookies});
2016-10-06 16:52:26 +00:00
jar = CookieJar.fromJSON(copy);
} catch (e) {
console.log('Failed to initialize cookie jar', e);
2016-10-06 16:52:26 +00:00
jar = new CookieJar();
}
2016-10-06 16:52:26 +00:00
jar.rejectPublicSuffixes = false;
jar.looseMode = true;
return jar;
}
export function cookieToString (cookie) {
2017-10-16 22:19:16 +00:00
// Cookie can either be a plain JS object or Cookie instance
if (!(cookie instanceof Cookie)) {
cookie = Cookie.fromJSON(cookie);
}
let 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;
}