UNPKG

@cfworker/cosmos

Version:

Azure Cosmos DB client for Cloudflare Workers and service workers

50 lines (49 loc) 1.55 kB
const readSessionNotAvailableSubstatus = '1002'; export function readSessionNotAvailable(response) { return (response.status === 404 && response.headers.get('x-ms-substatus') === readSessionNotAvailableSubstatus); } export 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 }; } export 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; } }