@translated/lara
Version:
Official Lara SDK for JavaScript and Node.js
63 lines (62 loc) • 2.35 kB
JavaScript
;
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) {
var _a;
let requestBody;
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)) {
for (const v of value)
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
});
if ((_a = response.headers.get("Content-Type")) === null || _a === void 0 ? void 0 : _a.includes("text/csv")) {
return {
statusCode: response.status,
body: {
content: await response.text()
}
};
}
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;