balena-sdk
Version:
The Balena JavaScript SDK
70 lines (69 loc) • 2.37 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PinejsClient = void 0;
const tslib_1 = require("tslib");
const url = tslib_1.__importStar(require("url"));
const errors = tslib_1.__importStar(require("balena-errors"));
const pinejs_client_core_1 = require("pinejs-client-core");
/**
* @class
* @classdesc A PineJS Client subclass to communicate with balena.
* @private
*
* @description
* This subclass makes use of the [balena-request](https://github.com/balena-io-modules/balena-request) project.
*/
class PinejsClient extends pinejs_client_core_1.PinejsClientCore {
constructor(params, backendParams) {
super({
...params,
apiPrefix: url.resolve(backendParams.apiUrl, `/${backendParams.apiVersion}/`),
});
this.backendParams = backendParams;
this.backendParams = backendParams;
this.API_URL = backendParams.apiUrl;
this.API_VERSION = backendParams.apiVersion;
}
/**
* @summary Perform a network request to balena.
* @method
* @private
*
* @param {Object} options - request options
* @returns {Promise<any>} response body
*
* @todo Implement caching support.
*/
async _request(options) {
const { apiKey, apiUrl, auth, request } = this.backendParams;
const hasKey = await auth.hasKey();
const authenticated = hasKey || (apiKey != null && apiKey.length > 0);
options = {
apiKey,
baseUrl: apiUrl,
sendToken: authenticated && !options.anonymous,
...options,
};
try {
const { body } = await request.send(options);
return body;
}
catch (err) {
if (err.statusCode !== 401) {
throw err;
}
// Always return the API error when the anonymous flag is used.
if (options.anonymous) {
throw err;
}
// We want to allow unauthenticated users to make requests
// to public resources, but still reject with a NotLoggedIn
// error if the response ends up being a 401.
if (!authenticated) {
throw new errors.BalenaNotLoggedIn();
}
throw err;
}
}
}
exports.PinejsClient = PinejsClient;