linky
Version:
Easily retrieve your Linky power consumption
85 lines (84 loc) • 3.02 kB
JavaScript
import axios, { AxiosError } from 'axios';
import qs from 'qs';
import jwt from 'jsonwebtoken';
const API_HOST = 'https://conso.boris.sh';
export var DataType;
(function (DataType) {
DataType["daily_consumption"] = "daily_consumption";
DataType["consumption_load_curve"] = "consumption_load_curve";
DataType["consumption_max_power"] = "consumption_max_power";
DataType["daily_production"] = "daily_production";
DataType["production_load_curve"] = "production_load_curve";
})(DataType || (DataType = {}));
export class APIError extends Error {
constructor(err, code, response) {
super('Conso API a répondu avec une erreur');
this.err = err;
this.code = code;
this.response = response;
}
toString() {
return (`Conso API a répondu avec une erreur\nCode: ${this.code}\nRéponse : ` + JSON.stringify(this.response, null, 4));
}
}
export class Session {
constructor(token, prm) {
this.token = token;
this.prm = prm;
this.prms = [];
this.userAgent = '@bokub/linky';
try {
const decoded = jwt.decode(token);
this.prms = decoded.sub;
}
catch (err) {
throw new Error('Le token est invalide');
}
if (!Array.isArray(this.prms) || this.prms.length === 0) {
throw new Error('Le token est invalide');
}
if (this.prm && !this.prms.includes(this.prm)) {
throw new Error("Ce token ne permet pas d'accéder au PRM " + this.prm);
}
}
getDailyConsumption(start, end) {
return this.callApi(DataType.daily_consumption, start, end);
}
getLoadCurve(start, end) {
return this.callApi(DataType.consumption_load_curve, start, end);
}
getMaxPower(start, end) {
return this.callApi(DataType.consumption_max_power, start, end);
}
getDailyProduction(start, end) {
return this.callApi(DataType.daily_production, start, end);
}
getProductionLoadCurve(start, end) {
return this.callApi(DataType.production_load_curve, start, end);
}
callApi(type, start, end) {
const url = `${API_HOST}/api/${type}?${qs.stringify({
start: start,
end: end,
prm: this.prm || this.prms[0],
})}`;
return axios
.get(url, {
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/json',
'User-Agent': this.userAgent,
},
})
.then((res) => res.data)
.catch((err) => {
if (err.response) {
throw new APIError(err, err.response.status, err.response.data);
}
if (err.request) {
throw new Error(`Aucune réponse de Conso API\nRequête : ` + JSON.stringify(err.request, null, 4));
}
throw new Error(`Impossible d'appeler Conso API\nErreur : ${err.message}`);
});
}
}