UNPKG

@justwicked/tmdb-api-wrapper

Version:

A lightweight TypeScript wrapper for the TMDB API.

74 lines (73 loc) 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class HttpConnector { constructor(baseUrl, apiKey, defaultOptions = {}) { var _a; this.baseUrl = baseUrl; this.headers = { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', ...((_a = defaultOptions.headers) !== null && _a !== void 0 ? _a : {}), }; this.defaultOptions = defaultOptions; } async request(endpoint, options = {}) { var _a, _b, _c, _d; let url = ((_a = options.baseUrl) !== null && _a !== void 0 ? _a : this.baseUrl) + endpoint; // Merge and sanitize params const allParams = { ...this.defaultOptions.params, ...options.params }; const sanitizedParams = {}; Object.entries(allParams !== null && allParams !== void 0 ? allParams : {}).forEach(([key, value]) => { if (value !== undefined && value !== null) { sanitizedParams[key] = String(value); } }); if (Object.keys(sanitizedParams).length > 0) { url += `?${new URLSearchParams(sanitizedParams).toString()}`; } const headers = { ...this.headers, ...((_b = options.headers) !== null && _b !== void 0 ? _b : {}) }; const next = { ...((_c = this.defaultOptions.next) !== null && _c !== void 0 ? _c : {}), ...((_d = options.next) !== null && _d !== void 0 ? _d : {}) }; const fetchConfig = { ...this.defaultOptions, ...options, headers, }; if (Object.keys(next).length > 0) fetchConfig.next = next; const res = await fetch(url, fetchConfig); if (!res.ok) { const errorText = await res.text(); throw new Error(`HTTP ${res.status}: ${errorText}`); } const contentType = res.headers.get('content-type'); if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { return (await res.json()); } return (await res.text()); } get(endpoint, options) { return this.request(endpoint, { ...options, method: 'GET' }); } post(endpoint, body, options) { return this.request(endpoint, { ...options, method: 'POST', body: body ? JSON.stringify(body) : undefined, }); } put(endpoint, body, options) { return this.request(endpoint, { ...options, method: 'PUT', body: body ? JSON.stringify(body) : undefined, }); } delete(endpoint, body, options) { return this.request(endpoint, { ...options, method: 'DELETE', body: body ? JSON.stringify(body) : undefined, }); } } exports.default = HttpConnector;