UNPKG

@perceptr/web-sdk

Version:

Perceptr Web SDK for recording and monitoring user sessions

95 lines (94 loc) 3.84 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import axios, { AxiosError } from "axios"; import { logger } from "../../utils/logger"; export class ApiService { constructor(config) { this.host = this.getHost(config.env); this.apiUrl = `${this.host}/api/v1/per/${config.projectId}`; } getHost(env) { switch (env) { case "local": return "http://localhost:8000"; case "dev": return "https://api-dev.perceptr.io"; case "stg": return "https://api-stg.perceptr.io"; case "prod": return "https://api.perceptr.io"; default: return "https://api.perceptr.io"; } } checkValidProjectId() { return __awaiter(this, void 0, void 0, function* () { try { const url = `${this.apiUrl}/check`; const response = yield axios.get(url); return response.data.success; } catch (error) { logger.error(`Error checking project ID:`, error); return false; } }); } getUploadBufferUrl(sessionId) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; try { const url = `${this.apiUrl}/r/${sessionId}/batch`; const response = yield axios.get(url); return response.data.url; } catch (error) { if (error instanceof AxiosError) { if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 400 && ((_b = error.response) === null || _b === void 0 ? void 0 : _b.data.detail) === "processing already started") { logger.debug(`Processing already started for session ${sessionId} skipping...`); return null; } } throw error; } }); } processSession(sessionId) { return __awaiter(this, void 0, void 0, function* () { try { const url = `${this.apiUrl}/r/${sessionId}/process`; yield axios.post(url); } catch (error) { // we assume this is because the session is already being processed logger.error(`Error processing session ${sessionId}:`, error); } }); } sendEvents(buffer) { return __awaiter(this, void 0, void 0, function* () { const url = yield this.getUploadBufferUrl(buffer.sessionId); if (!url) { return; } yield axios.put(url, buffer, { headers: { "Content-Type": "application/json", }, }); logger.debug(`Successfully uploaded events to S3 ${buffer.sessionId} (${buffer.size} bytes)`); if (buffer.isSessionEnded) { yield this.processSession(buffer.sessionId); logger.debug(`Session ${buffer.sessionId} triggered`); } }); } }