UNPKG

camstreamerlib

Version:

Helper library for CamStreamer ACAP applications.

90 lines (89 loc) 2.94 kB
import { ErrorWithResponse, ParsingBlobError } from '../errors/errors'; import { ProxyClient } from './ProxyClient'; import { paramToUrl } from './utils'; export class BasicAPI { client; constructor(client) { this.client = client; } getClient(proxyParams) { return proxyParams ? new ProxyClient(this.client, proxyParams) : this.client; } async _getJson(path, parameters, options) { const agent = this.getClient(options?.proxyParams); const res = await agent.get({ path, parameters, timeout: options?.timeout }); if (res.ok) { return await res.json(); } else { throw new ErrorWithResponse(res); } } async _getText(path, parameters, options) { const agent = this.getClient(options?.proxyParams); const res = await agent.get({ path, parameters, timeout: options?.timeout }); if (res.ok) { return await res.text(); } else { throw new ErrorWithResponse(res); } } async _getBlob(path, parameters, options) { const agent = this.getClient(options?.proxyParams); const res = await agent.get({ path, parameters, timeout: options?.timeout }); if (res.ok) { return await this.parseBlobResponse(res); } else { throw new ErrorWithResponse(res); } } async parseBlobResponse(response) { try { return (await response.blob()); } catch (err) { throw new ParsingBlobError(err); } } async _post(path, data, parameters, options, headers) { const agent = this.getClient(options?.proxyParams); const res = await agent.post({ path, data, parameters, headers, timeout: options?.timeout }); if (res.ok) { return await res.json(); } else { throw new ErrorWithResponse(res); } } async _postJsonEncoded(path, data, parameters, options) { const agent = this.getClient(options?.proxyParams); const jsonData = JSON.stringify(data); const res = await agent.post({ path, data: jsonData, parameters, headers: { 'Content-Type': 'application/json' }, timeout: options?.timeout, }); if (!res.ok) { throw new ErrorWithResponse(res); } return res; } async _postUrlEncoded(path, data, options) { const encodedData = paramToUrl(data); const agent = this.getClient(options?.proxyParams); const res = await agent.post({ path, data: encodedData, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: options?.timeout, }); if (!res.ok) { throw new ErrorWithResponse(res); } return res; } }