UNPKG

homebridge-vicare

Version:
78 lines 3.73 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; export class RequestService { constructor(log, clientId) { this.log = log; this.clientId = clientId; } authorizedRequest(url_1) { return __awaiter(this, arguments, void 0, function* (url, method = 'get', config, retries = 0) { if (retries >= 3) { throw new Error('Could not refresh authentication token.'); } try { return yield this.request(url, method, Object.assign({ headers: Object.assign({ Authorization: `Bearer ${this.accessToken}` }, config === null || config === void 0 ? void 0 : config.headers) }, config)); } catch (error) { return yield this.checkForTokenExpiration(error, url, method, config, retries); } }); } checkForTokenExpiration(body_1, url_1) { return __awaiter(this, arguments, void 0, function* (body, url, method = 'get', config, retries = 1) { if (body.error === 'EXPIRED TOKEN') { const { access_token } = yield this.refreshAuth(); this.accessToken = access_token; return yield this.authorizedRequest(url, method, config, ++retries); } else { throw body; } }); } request(url, method, config) { return __awaiter(this, void 0, void 0, function* () { return yield fetch(url, Object.assign({ headers: Object.assign({ Accept: 'application/json' }, config === null || config === void 0 ? void 0 : config.headers), method }, config)); }); } refreshAuth() { return __awaiter(this, void 0, void 0, function* () { if (!this.refreshToken) { throw new Error('Refresh token is not set. Please authenticate first.'); } const tokenUrl = 'https://iam.viessmann-climatesolutions.com/idp/v3/token'; const params = new URLSearchParams(); params.set('client_id', this.clientId); params.set('grant_type', 'refresh_token'); params.set('refresh_token', this.refreshToken); this.log.debug('Refreshing authorization ...'); try { const response = yield this.authorizedRequest(tokenUrl, 'post', { body: params, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }); let tokenResponse = (yield response.json()); if (!response.ok) { throw new Error(JSON.stringify(tokenResponse, null, 2)); } this.log('Successfully refreshed authorization.'); this.accessToken = tokenResponse.access_token; return tokenResponse; } catch (error) { this.log.error('Error refreshing authorization:', error); throw error; } }); } } //# sourceMappingURL=RequestService.js.map