UNPKG

@cfworker/cosmos

Version:

Azure Cosmos DB client for Cloudflare Workers and service workers

56 lines (55 loc) 1.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DefaultSessionContainer = void 0; exports.readSessionNotAvailable = readSessionNotAvailable; exports.getCollectionId = getCollectionId; const readSessionNotAvailableSubstatus = '1002'; function readSessionNotAvailable(response) { return (response.status === 404 && response.headers.get('x-ms-substatus') === readSessionNotAvailableSubstatus); } function getCollectionId({ url, headers }) { const path = headers.get('x-ms-alt-content-path') ?? new URL(url).pathname.substr(1); const [, dbId, colls, collId] = path.split('/'); if (colls !== 'colls' || !collId) { return null; } return { dbId, collId }; } class DefaultSessionContainer { tokens; constructor(tokens = {}) { this.tokens = tokens; } setRequestSession(request) { if (request.headers.get('x-ms-consistency-level') !== 'Session') { return; } const ids = getCollectionId(request); if (!ids) { return; } const token = this.tokens?.[ids.dbId]?.[ids.collId]; if (token) { request.headers.set('x-ms-session-token', token); } } readResponseSession(response) { const ids = getCollectionId(response); if (!ids) { return; } if (readSessionNotAvailable(response)) { if (this.tokens[ids.dbId]) { delete this.tokens[ids.dbId][ids.collId]; } } const token = response.headers.get('x-ms-session-token'); if (!token) { return; } this.tokens[ids.dbId] ??= {}; this.tokens[ids.dbId][ids.collId] = token; } } exports.DefaultSessionContainer = DefaultSessionContainer;