@powercalc/power-router 1.0.15 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/app.d.ts +1 -0
  2. package/dist/app.js +26 -0
  3. package/dist/genTypes.d.ts +4 -0
  4. package/dist/genTypes.js +64 -0
  5. package/dist/index.d.ts +8 -2
  6. package/dist/index.js +78 -4
  7. package/dist/load.d.ts +7 -0
  8. package/dist/load.js +50 -0
  9. package/dist/router/controllers/LoadAndParse.js +68 -0
  10. package/dist/router/controllers/Router.js +116 -0
  11. package/dist/router/index.d.ts +2 -0
  12. package/dist/router/index.js +5 -0
  13. package/dist/{interfaces → router/interfaces}/config.js +0 -1
  14. package/dist/{interfaces → router/interfaces}/entsoe.js +0 -1
  15. package/dist/{interfaces → router/interfaces}/queryoptions.js +0 -1
  16. package/dist/{interfaces → router/interfaces}/types.js +0 -1
  17. package/dist/{services → router/services}/CommonTimestamps.js +0 -1
  18. package/dist/router/services/Eurostat.js +85 -0
  19. package/dist/router/services/LoadService.js +101 -0
  20. package/dist/router/services/Loader.js +138 -0
  21. package/dist/{services → router/services}/ParseEdifact.js +0 -1
  22. package/dist/{services → router/services}/ParseInstalled.js +0 -1
  23. package/dist/router/services/batch/maxHydrofill.js +82 -0
  24. package/package.json +2 -2
  25. package/src/router/controllers/LoadAndParse.ts +0 -2
  26. package/dist/controllers/LoadAndParse.js +0 -72
  27. package/dist/controllers/LoadAndParse.js.map +0 -1
  28. package/dist/controllers/Router.js +0 -106
  29. package/dist/controllers/Router.js.map +0 -1
  30. package/dist/index.js.map +0 -1
  31. package/dist/interfaces/config.js.map +0 -1
  32. package/dist/interfaces/entsoe.js.map +0 -1
  33. package/dist/interfaces/queryoptions.js.map +0 -1
  34. package/dist/interfaces/types.js.map +0 -1
  35. package/dist/services/CommonTimestamps.js.map +0 -1
  36. package/dist/services/Eurostat.js +0 -73
  37. package/dist/services/Eurostat.js.map +0 -1
  38. package/dist/services/LoadService.js +0 -83
  39. package/dist/services/LoadService.js.map +0 -1
  40. package/dist/services/Loader.js +0 -122
  41. package/dist/services/Loader.js.map +0 -1
  42. package/dist/services/ParseEdifact.js.map +0 -1
  43. package/dist/services/ParseInstalled.js.map +0 -1
  44. package/dist/services/batch/maxHydrofill.js +0 -66
  45. package/dist/services/batch/maxHydrofill.js.map +0 -1
  46. /package/dist/{controllers → router/controllers}/LoadAndParse.d.ts +0 -0
  47. /package/dist/{controllers → router/controllers}/Router.d.ts +0 -0
  48. /package/dist/{interfaces → router/interfaces}/config.d.ts +0 -0
  49. /package/dist/{interfaces → router/interfaces}/entsoe.d.ts +0 -0
  50. /package/dist/{interfaces → router/interfaces}/queryoptions.d.ts +0 -0
  51. /package/dist/{interfaces → router/interfaces}/types.d.ts +0 -0
  52. /package/dist/{services → router/services}/CommonTimestamps.d.ts +0 -0
  53. /package/dist/{services → router/services}/Eurostat.d.ts +0 -0
  54. /package/dist/{services → router/services}/LoadService.d.ts +0 -0
  55. /package/dist/{services → router/services}/Loader.d.ts +0 -0
  56. /package/dist/{services → router/services}/ParseEdifact.d.ts +0 -0
  57. /package/dist/{services → router/services}/ParseInstalled.d.ts +0 -0
  58. /package/dist/{services → router/services}/batch/maxHydrofill.d.ts +0 -0
package/dist/app.d.ts ADDED
@@ -0,0 +1 @@
1
+ import 'reflect-metadata';
package/dist/app.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ require("reflect-metadata");
7
+ process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = '0';
8
+ const express_1 = __importDefault(require("express"));
9
+ const cors_1 = __importDefault(require("cors"));
10
+ const path_1 = require("path");
11
+ const process_1 = require("process");
12
+ const Router_1 = require("./router/controllers/Router");
13
+ const app = (0, express_1.default)();
14
+ const port = 30000;
15
+ const config = {
16
+ securityToken: '1c608639-afff-4d73-bfe1-a960fe7ea8da',
17
+ cacheDir: (0, path_1.join)((0, process_1.cwd)(), 'data'),
18
+ entsoeDomain: "https://web-api.tp.entsoe.eu"
19
+ };
20
+ app.use((0, cors_1.default)());
21
+ app.use('/entsoe', Router_1.PowerRouter.init(config));
22
+ app.use('/public', express_1.default.static('public'));
23
+ // app.use('/config', express.static('dist/config', { maxAge: 100000 }));
24
+ app.listen(port, () => {
25
+ console.log(`Server listening on port ${port}`);
26
+ });
@@ -0,0 +1,4 @@
1
+ export declare class GenTypes {
2
+ static getTypes(country: string): Promise<any[]>;
3
+ static makeGen(gen: any, load: any, price: any): any;
4
+ }
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.GenTypes = void 0;
13
+ const node_zlib_1 = require("node:zlib");
14
+ const load_1 = require("./load");
15
+ const promises_1 = require("node:fs/promises");
16
+ class GenTypes {
17
+ static getTypes(country) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ let types = [];
20
+ const minYear = 2015;
21
+ const maxYear = 2023;
22
+ let min;
23
+ let max;
24
+ for (let year = minYear; year <= maxYear; year++) {
25
+ for (let month = 1; month <= 12; month++) {
26
+ const gen = yield load_1.Load.getGeneration(country, year, month);
27
+ const price = yield load_1.Load.getPrice(country, year, month);
28
+ const load = yield load_1.Load.getLoad(country, year, month);
29
+ const all = this.makeGen(gen, load, price);
30
+ const gzipfilename = `data/gzip/${country}-${year}-${month}.json.gzip`;
31
+ const filename = `data/generation/${country}-${year}-${month}.json`;
32
+ const buf = Buffer.from(JSON.stringify(all), 'utf-8');
33
+ (0, node_zlib_1.gzip)(buf, (_, result) => __awaiter(this, void 0, void 0, function* () {
34
+ var _a;
35
+ yield (0, promises_1.writeFile)(gzipfilename, result, 'utf-8');
36
+ // console.log(gen.dataset.map((item:any) => item.label))
37
+ types = types.concat(((_a = gen.dataset) === null || _a === void 0 ? void 0 : _a.map((item) => item.psrType)) || []);
38
+ }));
39
+ yield (0, promises_1.writeFile)(filename, JSON.stringify(all, null, 2), 'utf-8');
40
+ }
41
+ }
42
+ return [...new Set(types)].sort();
43
+ });
44
+ }
45
+ static makeGen(gen, load, price) {
46
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
47
+ const all = {};
48
+ if ((_a = gen.dataset) === null || _a === void 0 ? void 0 : _a[0]) {
49
+ all.time = (_d = (_c = (_b = gen.dataset) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.map((item) => item.x);
50
+ gen.dataset.forEach((dataset) => {
51
+ all[dataset.psrType] = dataset.data.map((item) => item.y);
52
+ });
53
+ }
54
+ if ((_f = (_e = load === null || load === void 0 ? void 0 : load.dataset) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.data) {
55
+ all.A05 = load.dataset[0].data.map((item) => item.y);
56
+ }
57
+ if ((_g = price === null || price === void 0 ? void 0 : price.dataset) === null || _g === void 0 ? void 0 : _g[0]) {
58
+ all.price = price.dataset[0].data.map((item) => item.y);
59
+ }
60
+ console.log((_h = all.time) === null || _h === void 0 ? void 0 : _h.length, (_j = all.A05) === null || _j === void 0 ? void 0 : _j.length, (_k = all.price) === null || _k === void 0 ? void 0 : _k.length);
61
+ return all;
62
+ }
63
+ }
64
+ exports.GenTypes = GenTypes;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,8 @@
1
- export { PowerRouter } from './controllers/Router';
2
- export { Config } from './interfaces/config';
1
+ export declare class Convert {
2
+ static start(): Promise<void>;
3
+ static getCountries(): Promise<any>;
4
+ static getGeneration(countryCode: string): Promise<any>;
5
+ static getLoad(countryCode: string): Promise<any>;
6
+ static getPrice(countryCode: string): Promise<any>;
7
+ static getHydrofill(countryCode: string): Promise<any>;
8
+ }
package/dist/index.js CHANGED
@@ -1,6 +1,80 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PowerRouter = void 0;
4
- var Router_1 = require("./controllers/Router");
5
- Object.defineProperty(exports, "PowerRouter", { enumerable: true, get: function () { return Router_1.PowerRouter; } });
6
- //# sourceMappingURL=index.js.map
12
+ exports.Convert = void 0;
13
+ const genTypes_1 = require("./genTypes");
14
+ const maxHydrofill_1 = require("./router/services/batch/maxHydrofill");
15
+ const promises_1 = require("node:fs/promises");
16
+ class Convert {
17
+ static start() {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ const countries = yield this.getCountries();
20
+ console.log(countries);
21
+ for (const country of countries) {
22
+ const types = yield genTypes_1.GenTypes.getTypes(country.code);
23
+ country.types = types;
24
+ console.log(country.name, types.join(', '));
25
+ const h = yield maxHydrofill_1.Hydrofill.getMaxHydrofill(country.code);
26
+ if (h.max) {
27
+ const GW = Math.round(h.max / 1000) + ' GW';
28
+ console.log(country.name, GW);
29
+ country.hydrofill = {
30
+ min: h.min,
31
+ max: h.max
32
+ };
33
+ }
34
+ const gen = yield this.getGeneration(country.code);
35
+ const load = yield this.getLoad(country.code);
36
+ const price = yield this.getPrice(country.code);
37
+ const hydrofill = yield this.getHydrofill(country.code);
38
+ }
39
+ console.log(countries);
40
+ (0, promises_1.writeFile)('data/countrydata.json', JSON.stringify(countries, null, 2), 'utf-8');
41
+ });
42
+ }
43
+ static getCountries() {
44
+ return __awaiter(this, void 0, void 0, function* () {
45
+ const url = 'https://powercalculator.eu/entsoe/datalists/countries';
46
+ const response = yield fetch(url);
47
+ return yield response.json();
48
+ });
49
+ }
50
+ static getGeneration(countryCode) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/generation?year=2021&month=9`;
53
+ const response = yield fetch(url);
54
+ return yield response.json();
55
+ });
56
+ }
57
+ static getLoad(countryCode) {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/load?year=2021&month=9`;
60
+ const response = yield fetch(url);
61
+ return yield response.json();
62
+ });
63
+ }
64
+ static getPrice(countryCode) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/prices?year=2021&month=9`;
67
+ const response = yield fetch(url);
68
+ return yield response.json();
69
+ });
70
+ }
71
+ static getHydrofill(countryCode) {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/hydrofill?year=2021`;
74
+ const response = yield fetch(url);
75
+ return yield response.json();
76
+ });
77
+ }
78
+ }
79
+ exports.Convert = Convert;
80
+ Convert.start();
package/dist/load.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export declare class Load {
2
+ static getCountries(): Promise<any>;
3
+ static getGeneration(countryCode: string, year: number, month: number): Promise<any>;
4
+ static getLoad(countryCode: string, year: number, month: number): Promise<any>;
5
+ static getPrice(countryCode: string, year: number, month: number): Promise<any>;
6
+ static getHydrofill(countryCode: string, year: number): Promise<any>;
7
+ }
package/dist/load.js ADDED
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Load = void 0;
13
+ class Load {
14
+ static getCountries() {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ const url = 'https://powercalculator.eu/entsoe/datalists/countries';
17
+ const response = yield fetch(url);
18
+ return yield response.json();
19
+ });
20
+ }
21
+ static getGeneration(countryCode, year, month) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/generation?year=${year}&month=${month}`;
24
+ const response = yield fetch(url);
25
+ return yield response.json();
26
+ });
27
+ }
28
+ static getLoad(countryCode, year, month) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/load?year=${year}&month=${month}`;
31
+ const response = yield fetch(url);
32
+ return yield response.json();
33
+ });
34
+ }
35
+ static getPrice(countryCode, year, month) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/prices?year=${year}&month=${month}`;
38
+ const response = yield fetch(url);
39
+ return yield response.json();
40
+ });
41
+ }
42
+ static getHydrofill(countryCode, year) {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ const url = `https://powercalculator.eu/entsoe/${countryCode}/hydrofill?year=${year}`;
45
+ const response = yield fetch(url);
46
+ return yield response.json();
47
+ });
48
+ }
49
+ }
50
+ exports.Load = Load;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.LoadAndParse = void 0;
13
+ const path_1 = require("path");
14
+ const fs_1 = require("fs");
15
+ const LoadService_1 = require("../services/LoadService");
16
+ const queryoptions_1 = require("../interfaces/queryoptions");
17
+ class LoadAndParse {
18
+ constructor(config) {
19
+ this.country = '';
20
+ const countriesFile = (0, path_1.join)(__dirname, '../config/countries.json'); // Set the path to your config file
21
+ this.countries = JSON.parse((0, fs_1.readFileSync)(countriesFile, 'utf8')); // Read the config file from disk
22
+ this.loadService = new LoadService_1.LoadService(config);
23
+ }
24
+ get(req, chartType) {
25
+ var _a;
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ const country = req.params.country;
28
+ if (this.country !== country) {
29
+ console.log(`=========== ${country} =============`);
30
+ this.country = country;
31
+ }
32
+ const queryOptions = {};
33
+ const year = parseInt(req.params.year);
34
+ const month = parseInt(req.params.month);
35
+ if (req.query.posneg === queryoptions_1.PosNeg.POS || req.query.posneg === queryoptions_1.PosNeg.NEG) {
36
+ queryOptions.posneg = req.query.posneg;
37
+ }
38
+ if (typeof (req.query.format) === 'string' && Object.values(queryoptions_1.Format).includes(req.query.format)) {
39
+ queryOptions.format = req.query.format;
40
+ }
41
+ let reload = false;
42
+ if (typeof (req.headers.reload) === 'string') {
43
+ reload = true;
44
+ queryOptions.reload = true;
45
+ }
46
+ const countryCode = (_a = this.countries.find(item => item.name === country)) === null || _a === void 0 ? void 0 : _a.code;
47
+ if (!countryCode) {
48
+ throw new Error('Unknown country ' + country);
49
+ }
50
+ if (chartType === 'installed') {
51
+ return yield this.loadService.getInstalled(countryCode, reload);
52
+ }
53
+ if (chartType === 'power') {
54
+ return yield this.loadService.getPower(countryCode, year, month, queryOptions);
55
+ }
56
+ if (chartType === 'hydrofill') {
57
+ return yield this.loadService.getHydrofill(countryCode, reload);
58
+ }
59
+ if (chartType === 'fossil') {
60
+ return yield this.loadService.getFossil(countryCode);
61
+ }
62
+ if (chartType === 'countrydata') {
63
+ return yield this.loadService.getCountrydata(countryCode, reload);
64
+ }
65
+ });
66
+ }
67
+ }
68
+ exports.LoadAndParse = LoadAndParse;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PowerRouter = void 0;
13
+ const express_1 = require("express");
14
+ const crypto_1 = require("crypto");
15
+ const promises_1 = require("fs/promises");
16
+ const zlib_1 = require("zlib");
17
+ const node_buffer_1 = require("node:buffer");
18
+ const fs_1 = require("fs");
19
+ const LoadAndParse_1 = require("./LoadAndParse");
20
+ const path_1 = require("path");
21
+ class PowerRouter {
22
+ static init(config) {
23
+ console.log('init', config);
24
+ const router = (0, express_1.Router)();
25
+ router.get(`/:country/:year/:month`, (req, res) => __awaiter(this, void 0, void 0, function* () {
26
+ yield this.load(config, req, res, 'power');
27
+ }));
28
+ router.get(`/:country/fossil`, (req, res) => __awaiter(this, void 0, void 0, function* () {
29
+ yield this.load(config, req, res, 'fossil');
30
+ }));
31
+ router.get(`/:country/installed`, (req, res) => __awaiter(this, void 0, void 0, function* () {
32
+ yield this.load(config, req, res, 'installed');
33
+ }));
34
+ router.get(`/:country/hydrofill`, (req, res) => __awaiter(this, void 0, void 0, function* () {
35
+ yield this.load(config, req, res, 'hydrofill');
36
+ }));
37
+ router.get(`/:country/countrydata`, (req, res) => __awaiter(this, void 0, void 0, function* () {
38
+ yield this.load(config, req, res, 'countrydata');
39
+ }));
40
+ router.get('/types', (req, res) => __awaiter(this, void 0, void 0, function* () {
41
+ const filePath = (0, path_1.join)(__dirname, '..', 'config', 'types.json');
42
+ res.set({ 'Cache-Control': 'max-age=86400' });
43
+ res.sendFile(filePath);
44
+ }));
45
+ router.get('/countries', (req, res) => __awaiter(this, void 0, void 0, function* () {
46
+ const filePath = (0, path_1.join)(__dirname, '..', 'config', 'countrydata.json');
47
+ res.set({ 'Cache-Control': 'max-age=86400' });
48
+ res.sendFile(filePath);
49
+ }));
50
+ return router;
51
+ }
52
+ static load(config, req, res, type) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ const entsoeLoader = new LoadAndParse_1.LoadAndParse(config);
55
+ const cacheTime = this.calcCacheTime(req);
56
+ const successHeaders = {
57
+ 'Cache-Control': `public, max-age=${cacheTime}`,
58
+ 'Content-Encoding': 'gzip',
59
+ 'Content-Type': 'application/json'
60
+ };
61
+ try {
62
+ let cacheData;
63
+ const cacheKey = req.url;
64
+ const cacheFilePath = `${config.cacheDir}/${(0, crypto_1.createHash)('md5').update(cacheKey).digest('hex')}.json.gz`;
65
+ if (!(req.headers['reload'] === 'full')) {
66
+ // check if there is a cache file for this request
67
+ try {
68
+ const stats = yield (0, promises_1.stat)(cacheFilePath);
69
+ const modtime = stats.mtime.getTime();
70
+ // Check if the If-Modified-Since header matches the last modified date
71
+ const ifModifiedSince = req.headers['if-modified-since'];
72
+ if (ifModifiedSince && (modtime - new Date(ifModifiedSince).getTime()) < 5000) {
73
+ res.status(304).end();
74
+ return;
75
+ }
76
+ res.setHeader('Last-Modified', (new Date(modtime)).toUTCString());
77
+ res.set(successHeaders);
78
+ console.log('cached');
79
+ (0, fs_1.createReadStream)(cacheFilePath)
80
+ .pipe(res);
81
+ return;
82
+ }
83
+ catch (err) {
84
+ // no cache file found, continue with request
85
+ }
86
+ }
87
+ // if no cache hit, load data and store in cache
88
+ if (!cacheData) {
89
+ // LOAD THE DATA FROM SOURCE
90
+ const body = yield entsoeLoader.get(req, type);
91
+ const buf = node_buffer_1.Buffer.from(JSON.stringify(body), 'utf-8');
92
+ const cacheDataBuffer = (0, zlib_1.gzipSync)(buf);
93
+ yield (0, promises_1.writeFile)(cacheFilePath, cacheDataBuffer, 'utf-8');
94
+ res.setHeader('Last-Modified', (new Date()).toUTCString());
95
+ res.set(successHeaders);
96
+ res.send(cacheDataBuffer);
97
+ }
98
+ }
99
+ catch (e) {
100
+ console.log(e);
101
+ }
102
+ });
103
+ }
104
+ static calcCacheTime(req) {
105
+ const reqMonth = `${req.params.year} ${req.params.month}`;
106
+ const now = new Date();
107
+ const nowMonth = `${now.getFullYear()} ${now.getMonth() + 1}`;
108
+ if (reqMonth === nowMonth) {
109
+ return 5 * 60;
110
+ }
111
+ else {
112
+ return 3600 * 7;
113
+ }
114
+ }
115
+ }
116
+ exports.PowerRouter = PowerRouter;
@@ -0,0 +1,2 @@
1
+ export { PowerRouter } from './controllers/Router';
2
+ export { Config } from './interfaces/config';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PowerRouter = void 0;
4
+ var Router_1 = require("./controllers/Router");
5
+ Object.defineProperty(exports, "PowerRouter", { enumerable: true, get: function () { return Router_1.PowerRouter; } });
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=config.js.map
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=entsoe.js.map
@@ -13,4 +13,3 @@ var PosNeg;
13
13
  PosNeg["POS"] = "pos";
14
14
  PosNeg["NEG"] = "neg";
15
15
  })(PosNeg = exports.PosNeg || (exports.PosNeg = {}));
16
- //# sourceMappingURL=queryoptions.js.map
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=types.js.map
@@ -171,4 +171,3 @@ class CommonTimestamps {
171
171
  }
172
172
  }
173
173
  exports.CommonTimestamps = CommonTimestamps;
174
- //# sourceMappingURL=CommonTimestamps.js.map
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.EurostatAPI = void 0;
13
+ const fs_1 = require("fs");
14
+ const path_1 = require("path");
15
+ process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = '0';
16
+ class EurostatAPI {
17
+ constructor() {
18
+ this.countries = [];
19
+ this.fuels = {
20
+ gas: { chartType: 'NRG_CB_GASM', siec: 'G3000', nrg_bal: 'IC_OBS', unit: 'TJ_GCV', freq: 'M' },
21
+ gas4electricity: { chartType: 'NRG_CB_GASM', siec: 'G3000', nrg_bal: 'TI_EHG_MAP', unit: 'TJ_GCV', freq: 'M' },
22
+ gasoline: { chartType: 'NRG_CB_OILM', siec: 'O4652', nrg_bal: 'GID_OBS', unit: 'THS_T', freq: 'M' },
23
+ diesel: { chartType: 'NRG_CB_OILM', siec: 'O46711', nrg_bal: 'GID_OBS', unit: 'THS_T', freq: 'M' },
24
+ kerosin: { chartType: 'NRG_CB_OILM', siec: 'O4661', nrg_bal: 'GID_OBS', unit: 'THS_T', freq: 'M' }
25
+ };
26
+ this.energyConversionFactors = new Map([
27
+ ['KG_EQ', 12988.48],
28
+ ['TJ_GCV', Math.pow(10, 12)],
29
+ ['THS_T', 41868000000000], // joules per thousand metric tons of oil equivalent
30
+ ]);
31
+ const countryPath = (0, path_1.join)(__dirname, '..', 'config/countries.json');
32
+ const countriesString = (0, fs_1.readFileSync)(countryPath, 'utf-8');
33
+ this.countries = JSON.parse(countriesString);
34
+ }
35
+ convertToMWh(value, unit) {
36
+ const MWh = value * (this.energyConversionFactors.get(unit) || 0) / 3600 / Math.pow(10, 6);
37
+ return Math.round(MWh);
38
+ }
39
+ fetchData(url, type, unit) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ const response = yield fetch(url);
42
+ const data = yield response.json();
43
+ console.log(data, type, unit);
44
+ try {
45
+ const time = Object.keys(data.dimension.time.category.index);
46
+ return {
47
+ time: time.map(item => new Date(item).getTime()),
48
+ [type]: Object.values(data.value).map((item) => this.convertToMWh(item, unit))
49
+ };
50
+ }
51
+ catch (e) {
52
+ return {
53
+ [type]: [],
54
+ time: []
55
+ };
56
+ }
57
+ });
58
+ }
59
+ load(countryCode) {
60
+ var _a;
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ const countryShort = (_a = this.countries.find(item => item.code === countryCode)) === null || _a === void 0 ? void 0 : _a.short;
63
+ const baseUrl = 'https://ec.europa.eu/eurostat/api/dissemination/sdmx/2.1/data/';
64
+ const geo = `.${countryShort}`;
65
+ const promises = [];
66
+ for (const [type, fuel] of Object.entries(this.fuels)) {
67
+ const { chartType, siec, nrg_bal, unit, freq } = fuel;
68
+ const select = `${chartType}/${freq}.${nrg_bal}.${siec}.${unit}`;
69
+ const rest = `?format=JSON&lang=en&startPeriod=2015-01&endPeriod=2050-12`;
70
+ const url = `${baseUrl}${select}${geo}${rest}`;
71
+ console.log(url);
72
+ promises.push(this.fetchData(url, type, unit));
73
+ }
74
+ const res = yield Promise.all(promises);
75
+ console.log('---res---', res);
76
+ let merged = {};
77
+ res.forEach(item => {
78
+ merged = Object.assign(Object.assign({}, merged), item);
79
+ });
80
+ console.log('---merged----', merged);
81
+ return merged; // this.removeElGas(merged);
82
+ });
83
+ }
84
+ }
85
+ exports.EurostatAPI = EurostatAPI;