tsbase
Version:
Base class libraries for TypeScript
79 lines • 2.96 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CookieStorage = void 0;
const Strings_1 = require("../../System/Strings");
const module_1 = require("../../Patterns/CommandQuery/module");
const JsonSerializer_1 = require("../../Utility/Serialization/JsonSerializer");
const Cookies_1 = require("../../Utility/Web/Cookies");
var CookieOptionKeys;
(function (CookieOptionKeys) {
CookieOptionKeys["Domain"] = "domain";
CookieOptionKeys["Path"] = "path";
CookieOptionKeys["Expires"] = "expires";
CookieOptionKeys["Secure"] = "secure";
CookieOptionKeys["SameSite"] = "samesite";
CookieOptionKeys["Priority"] = "priority";
})(CookieOptionKeys || (CookieOptionKeys = {}));
/**
* Provides a generic interface for interacting with Cookies
*/
class CookieStorage {
constructor(serializer = new JsonSerializer_1.JsonSerializer(), mainDocument = document) {
this.serializer = serializer;
this.mainDocument = mainDocument;
}
Get(type, key) {
return new module_1.Query(() => {
const value = this.GetValue(key).Value;
if (value) {
return this.serializer.Deserialize(type, JSON.parse(value));
}
else {
throw new Error(`Unable to retrieve "${key}"`);
}
}).Execute();
}
Set(key, value, options) {
return new module_1.Command(() => {
this.SetValue(key, JSON.stringify(value), options);
}).Execute();
}
GetValue(key) {
return new module_1.Query(() => {
const cookieMap = Cookies_1.Cookies.GetCookieMap(this.mainDocument);
const value = cookieMap.get(key);
if (value) {
return value;
}
else {
throw new Error(`Unable to retrieve "${key}"`);
}
}).Execute();
}
SetValue(key, value, options = {
path: '/',
secure: true,
samesite: 'strict'
}) {
return new module_1.Command(() => {
const optionKeys = Object.values(CookieOptionKeys);
const expiresOptionString = options.expires ?
`expires=${options.expires.toUTCString()};` : Strings_1.Strings.Empty;
const optionsString = expiresOptionString + optionKeys.map(k => k !== CookieOptionKeys.Expires && !!options[k]
? `${k}=${options[k]};` : Strings_1.Strings.Empty).join('');
const newCookie = `${key}=${value};${optionsString}`;
this.mainDocument.cookie = newCookie;
}).Execute();
}
Remove(key, path = '/', domain) {
return new module_1.Command(() => {
this.SetValue(key, Strings_1.Strings.Empty, {
expires: new Date(0),
domain,
path
});
}).Execute();
}
}
exports.CookieStorage = CookieStorage;
//# sourceMappingURL=CookieStorage.js.map