UNPKG

tibber-api

Version:

Node.js module for connecting to Tibber API and extract data from your connected homes, including realtime data from Tibber Pulse.

192 lines 7.96 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.TibberQueryBase = void 0; const url = __importStar(require("url")); const HttpMethod_1 = require("./models/HttpMethod"); const websocketSubscriptionUrl_1 = require("../gql/websocketSubscriptionUrl"); const home_gql_1 = require("../gql/home.gql"); const TimeoutError_1 = require("./models/TimeoutError"); const HeaderManager_1 = require("../tools/HeaderManager"); const http_1 = require("http"); const https_1 = require("https"); const url_1 = require("url"); const util_1 = require("util"); // available in Node 12+ class TibberQueryBase { get requestTimeout() { return this._requestTimeout; } set requestTimeout(value) { this._requestTimeout = value; } get config() { return this._config; } set config(value) { this._config = value; } /** * */ constructor(config, requestTimeout = 30000) { this.active = false; this._config = config; this._headerManager = new HeaderManager_1.HeaderManager(config); this._requestTimeout = requestTimeout > 1000 ? requestTimeout : 1000; } /** * Try to parse a string and return a valid JSON object. * If string is not valid JSON, it will return an empty object instead. * @param input Input string to try to parse as a JSON object * @returns Parsed or empty Json object */ JsonTryParse(input) { try { // check if the string exists if (input) { const o = JSON.parse(input); // validate the result too if (o && o.constructor === Object) { return o; } } } catch (e) { // TODO - Add logging. } return { responseMessage: input }; } /** * * @param method HTTP method to use * @param uri Uri to use * @returns An object containing request options */ getRequestOptions(method, uri) { return { method, hostname: uri.hostname, port: uri.port, path: uri.path, headers: { Accept: 'application/json', Host: uri.hostname, 'User-Agent': this._headerManager.userAgent, 'Content-Type': 'application/json', Authorization: `Bearer ${this._config.apiEndpoint.apiKey}`, }, }; } /** * General GQL query * @param query GQL query. * @param variables Variables used by query parameter. * @return Query result as JSON data */ async query(query, variables) { return new Promise((resolve, reject) => { try { const uri = (0, url_1.parse)(this._config.apiEndpoint.queryUrl); const isHttps = uri.protocol === 'https:'; const client = isHttps ? https_1.request : http_1.request; const payload = JSON.stringify({ query, variables }); const data = new util_1.TextEncoder().encode(payload); const options = this.getRequestOptions(HttpMethod_1.HttpMethod.Post, uri); const req = client(options, (res) => { const chunks = []; res === null || res === void 0 ? void 0 : res.on('data', (chunk) => { chunks.push(chunk); }); res === null || res === void 0 ? void 0 : res.on('end', () => { var _a, _b, _c, _d; const body = Buffer.concat(chunks).toString('utf-8'); const parsed = this.JsonTryParse(body); const status = (_a = res === null || res === void 0 ? void 0 : res.statusCode) !== null && _a !== void 0 ? _a : 0; if (status >= 200 && status < 300) { resolve((_b = parsed.data) !== null && _b !== void 0 ? _b : parsed); } else { parsed.httpCode = status; parsed.statusCode = (_c = res === null || res === void 0 ? void 0 : res.statusCode) !== null && _c !== void 0 ? _c : 500; parsed.statusMessage = (_d = res === null || res === void 0 ? void 0 : res.statusMessage) !== null && _d !== void 0 ? _d : 'No response received'; if (!body) { parsed.message = 'Empty response from server'; } reject(parsed); } }); }); req.on('error', (err) => { reject(err); }); req.setTimeout(this._requestTimeout, () => { req.destroy(new TimeoutError_1.TimeoutError(`Request timeout for ${uri.href}`)); }); req.write(data); req.end(); } catch (err) { reject(err); } }); } /** * Get selected home with some selected properties, including address and owner. * @param homeId Tibber home ID * @return IHome object */ async getWebsocketSubscriptionUrl() { const result = await this.query(websocketSubscriptionUrl_1.qglWebsocketSubscriptionUrl); if (result && result.viewer && result.viewer.websocketSubscriptionUrl) { return new url.URL(result.viewer.websocketSubscriptionUrl); } throw new Error(result && result.error ? `Failed to get websocket subscription URL: ${result.error}` : 'Websocket subscription URL not found in response'); } /** * Get selected home with some selected properties, including address and owner. * @param homeId Tibber home ID * @return IHome object */ async getRealTimeEnabled(homeId) { var _a, _b, _c, _d; const variables = { homeId }; const result = await this.query(home_gql_1.gqlHomeRealTime, variables); return (_d = (_c = (_b = (_a = result === null || result === void 0 ? void 0 : result.viewer) === null || _a === void 0 ? void 0 : _a.home) === null || _b === void 0 ? void 0 : _b.features) === null || _c === void 0 ? void 0 : _c.realTimeConsumptionEnabled) !== null && _d !== void 0 ? _d : false; } } exports.TibberQueryBase = TibberQueryBase; //# sourceMappingURL=TibberQueryBase.js.map