zents
Version:
ZenTS is a Node.js & TypeScript MVC-Framework for building rich web applications, released as free and open-source software under the MIT License. It is designed for building web applications with modern tools and design patterns.
88 lines • 3.21 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cookie = void 0;
const cookie_1 = require("cookie");
const config_1 = require("../config/config");
const dayjs_1 = __importDefault(require("dayjs"));
const ms_1 = __importDefault(require("ms"));
class Cookie {
constructor(headers) {
var _a;
this.data = new Map();
this.modifiedKeys = new Set();
const cookies = cookie_1.parse((_a = headers.cookie) !== null && _a !== void 0 ? _a : '');
for (const [key, value] of Object.entries(cookies)) {
try {
const cookieValue = JSON.parse(value);
this.data.set(key, {
value: cookieValue,
options: this.getCookieOptions(),
});
}
catch (e) {
// silent
}
}
}
set(key, value, options) {
this.modifiedKeys.add(key);
this.data.set(key, {
value,
options: this.getCookieOptions(options),
});
}
get(key) {
if (!this.data.has(key)) {
return undefined;
}
return this.data.get(key).value;
}
has(key) {
return this.data.has(key);
}
serialize() {
const cookies = [];
for (const [key, cookie] of this.data) {
if (!this.modifiedKeys.has(key)) {
continue;
}
const options = cookie.options;
if (typeof cookie.options.expire === 'number') {
options.expires = dayjs_1.default().add(cookie.options.expire, 'millisecond').toDate();
delete cookie.options.expire;
}
else if (typeof cookie.options.expire === 'string') {
options.expires = dayjs_1.default().add(ms_1.default(cookie.options.expire), 'millisecond').toDate();
delete cookie.options.expire;
}
try {
cookies.push(cookie_1.serialize(key, JSON.stringify(cookie.value), options));
}
catch (e) {
// silent
}
}
return cookies.length ? cookies.join('; ') : '';
}
getCookieOptions(options) {
var _a, _b, _c, _d, _e;
let cookieOptions = {};
if (typeof options !== 'undefined') {
if (((_b = (_a = config_1.config.web) === null || _a === void 0 ? void 0 : _a.cookie) === null || _b === void 0 ? void 0 : _b.strategy) === 'merge') {
cookieOptions = Object.assign({}, (_c = config_1.config.web) === null || _c === void 0 ? void 0 : _c.cookie, options);
}
else {
cookieOptions = options;
}
}
else if ((_d = config_1.config.web) === null || _d === void 0 ? void 0 : _d.cookie) {
cookieOptions = (_e = config_1.config.web) === null || _e === void 0 ? void 0 : _e.cookie;
}
return cookieOptions;
}
}
exports.Cookie = Cookie;
//# sourceMappingURL=Cookie.js.map