mirror of
https://github.com/idanoo/GoScrobble.git
synced 2024-11-24 09:25:15 +00:00
54 lines
1.7 KiB
JavaScript
54 lines
1.7 KiB
JavaScript
import * as cookie from 'cookie';
|
|
export function hasDocumentCookie() {
|
|
// Can we get/set cookies on document.cookie?
|
|
return typeof document === 'object' && typeof document.cookie === 'string';
|
|
}
|
|
export function cleanCookies() {
|
|
document.cookie.split(';').forEach(function (c) {
|
|
document.cookie = c
|
|
.replace(/^ +/, '')
|
|
.replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
|
|
});
|
|
}
|
|
export function parseCookies(cookies, options) {
|
|
if (typeof cookies === 'string') {
|
|
return cookie.parse(cookies, options);
|
|
}
|
|
else if (typeof cookies === 'object' && cookies !== null) {
|
|
return cookies;
|
|
}
|
|
else {
|
|
return {};
|
|
}
|
|
}
|
|
export function isParsingCookie(value, doNotParse) {
|
|
if (typeof doNotParse === 'undefined') {
|
|
// We guess if the cookie start with { or [, it has been serialized
|
|
doNotParse =
|
|
!value || (value[0] !== '{' && value[0] !== '[' && value[0] !== '"');
|
|
}
|
|
return !doNotParse;
|
|
}
|
|
export function readCookie(value, options) {
|
|
if (options === void 0) { options = {}; }
|
|
var cleanValue = cleanupCookieValue(value);
|
|
if (isParsingCookie(cleanValue, options.doNotParse)) {
|
|
try {
|
|
return JSON.parse(cleanValue);
|
|
}
|
|
catch (e) {
|
|
// At least we tried
|
|
}
|
|
}
|
|
// Ignore clean value if we failed the deserialization
|
|
// It is not relevant anymore to trim those values
|
|
return value;
|
|
}
|
|
function cleanupCookieValue(value) {
|
|
// express prepend j: before serializing a cookie
|
|
if (value && value[0] === 'j' && value[1] === ':') {
|
|
return value.substr(2);
|
|
}
|
|
return value;
|
|
}
|