Skip to content

Instantly share code, notes, and snippets.

@webislife
Created April 19, 2019 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webislife/c64e172ff776371c64e62c10e0c5186b to your computer and use it in GitHub Desktop.
Save webislife/c64e172ff776371c64e62c10e0c5186b to your computer and use it in GitHub Desktop.
/**
* Cookies интерфейс для универсального node\broswer доступа к кукам
*/
export class Cookies {
constructor (options) {
this.env = options.env;
if(this.env === 'browser') {
this.Interface = new require('js-cookie');
}
if(this.env === "node") {
this.req = options.req;
this.res = options.res;
this.Interface = options.req.cookies;
}
}
/**
* Set cookie
* @param {String} key
* @param {String} value
* @param {Object} attributes {domain, expires, path, secure}
*/
set(key, value, attributes = {}) {
if(this.env === "node") {
this.res.setCookie(key, value, attributes);
} else {
this.Interface.set(key, value, attributes);
}
}
/**
* Get cookie by key
* @param {String} key
*/
get(key) {
let res = null;
if(this.env === "node") {
res = this.Interface[key];
} else {
res = this.Interface.get(key);
}
return res;
}
/**
* Remove cookie by key
* @param {string} key
* @param {object} attributes {path}
*/
clear(key, attributes = {}) {
if(this.env === "node") {
this.res.clearCookie(key, attributes);
} else {
this.Interface.remove(key, attributes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment