UNPKG

@translated/lara

Version:

Official Lara SDK for JavaScript and Node.js

51 lines (50 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BrowserLaraClient = void 0; const client_1 = require("./client"); function hasDefaultPort(port, secure) { return port === 80 && !secure || port === 443 && secure; } /** @internal */ class BrowserLaraClient extends client_1.LaraClient { constructor(baseUrl, accessKeyId, accessKeySecret) { super(accessKeyId, accessKeySecret); let url = `${baseUrl.secure ? "https" : "http"}://${baseUrl.hostname}`; if (!hasDefaultPort(baseUrl.port, baseUrl.secure)) url += `:${baseUrl.port}`; this.baseUrl = url; } async send(path, headers, body) { let requestBody = undefined; if (body) { if (headers["Content-Type"] === "multipart/form-data") { delete headers["Content-Type"]; // browser will set it automatically const formBody = new FormData(); for (const [key, value] of Object.entries(body)) { if (!value) continue; if (Array.isArray(value)) value.forEach(v => formBody.append(key, v)); else formBody.append(key, value); } requestBody = formBody; } else { requestBody = JSON.stringify(body, undefined, 0); } } const response = await fetch(this.baseUrl + path, { headers: headers, method: "POST", body: requestBody }); return { statusCode: response.status, body: await response.json() }; } wrapMultiPartFile(file) { if (file instanceof File) return file; throw new TypeError(`Invalid file input in the browser. Expected an instance of File but received ${typeof file}.`); } } exports.BrowserLaraClient = BrowserLaraClient;