insomnia/packages/insomnia-cookies/index.js
Gregory Schier 549ce23ce8
Merge All Repositories into Monorepo for easier maintenance (#629)
* All projects into monorepo

* Update CI

* More CI updates

* Extracted a bunch of things into packages

* Publish

 - insomnia-plugin-base64@1.0.1
 - insomnia-plugin-default-headers@1.0.2
 - insomnia-plugin-file@1.0.1
 - insomnia-plugin-hash@1.0.1
 - insomnia-plugin-now@1.0.1
 - insomnia-plugin-request@1.0.1
 - insomnia-plugin-response@1.0.1
 - insomnia-plugin-uuid@1.0.1
 - insomnia-cookies@0.0.2
 - insomnia-importers@1.5.2
 - insomnia-prettify@0.0.3
 - insomnia-url@0.0.2
 - insomnia-xpath@0.0.2

* A bunch of small fixes

* Improved build script

* Fixed

* Merge dangling files

* Usability refactor

* Handle duplicate plugin names
2017-11-26 20:45:40 +00:00

63 lines
1.5 KiB
JavaScript

const {CookieJar, Cookie} = require('tough-cookie');
/**
* Get a list of cookie objects from a request.jar()
*
* @param jar
*/
module.exports.cookiesFromJar = function (jar) {
return new Promise(resolve => {
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()));
}
});
});
};
/**
* Get a request.jar() from a list of cookie objects
*
* @param cookies
*/
module.exports.jarFromCookies = function (cookies) {
let jar;
try {
// For some reason, fromJSON modifies `cookies`. Create a copy first
// just to be sure
const copy = JSON.stringify({cookies});
jar = CookieJar.fromJSON(copy);
} catch (e) {
console.log('[cookies] Failed to initialize cookie jar', e);
jar = new CookieJar();
}
jar.rejectPublicSuffixes = false;
jar.looseMode = true;
return jar;
};
module.exports.cookieToString = function (cookie) {
// 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;
};