@vtex/api
Version:
VTEX I/O API client
77 lines (76 loc) • 2.76 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Session = void 0;
const cookie_1 = __importDefault(require("cookie"));
const JanusClient_1 = require("./JanusClient");
const SESSION_COOKIE = 'vtex_session';
const routes = {
base: '/api/sessions',
};
class Session extends JanusClient_1.JanusClient {
constructor() {
super(...arguments);
/**
* Get the session data using the given token
*/
this.getSession = async (token, items, tracingConfig) => {
var _a;
const metric = 'session-get';
const { data: sessionData, headers } = await this.http.getRaw(routes.base, {
headers: {
'Content-Type': 'application/json',
Cookie: `vtex_session=${token};`,
},
metric,
params: {
items: items.join(','),
},
tracing: {
requestSpanNameSuffix: metric,
...tracingConfig === null || tracingConfig === void 0 ? void 0 : tracingConfig.tracing,
},
});
return {
sessionData,
sessionToken: (_a = extractSessionCookie(headers)) !== null && _a !== void 0 ? _a : token,
};
};
/**
* Update the public portion of this session
*/
this.updateSession = (key, value, items, token, tracingConfig) => {
const data = { public: { [key]: { value } } };
const metric = 'session-update';
const config = {
headers: {
'Content-Type': 'application/json',
Cookie: `vtex_session=${token};`,
},
metric,
params: {
items: items.join(','),
},
tracing: {
requestSpanNameSuffix: metric,
...tracingConfig === null || tracingConfig === void 0 ? void 0 : tracingConfig.tracing,
},
};
return this.http.post(routes.base, data, config);
};
}
}
exports.Session = Session;
function extractSessionCookie(headers) {
var _a;
for (const setCookie of (_a = headers['set-cookie']) !== null && _a !== void 0 ? _a : []) {
const parsedCookie = cookie_1.default.parse(setCookie);
const sessionCookie = parsedCookie[SESSION_COOKIE];
if (sessionCookie != null) {
return sessionCookie;
}
}
return null;
}