-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
node_helper.js
110 lines (100 loc) · 2.87 KB
/
node_helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* @file node_helper.js
*
* @author fewieden
* @license MIT
*
* @see https://github.com/fewieden/MMM-Fuel
*/
/**
* @external node_helper
* @see https://github.com/MichMich/MagicMirror/blob/master/modules/node_modules/node_helper/index.js
*/
const NodeHelper = require('node_helper');
/**
* @external logger
* @see https://github.com/MichMich/MagicMirror/blob/master/js/logger.js
*/
const Log = require('logger');
/**
* @external fs
* @see https://nodejs.org/api/fs.html
*/
const fs = require('fs/promises');
/**
* @external path
* @see https://nodejs.org/api/path.html
*/
const path = require('path');
/**
* @module node_helper
* @description Backend for the module to query data from the API providers.
*
* @requires external:fs
* @requires external:path
* @requires external:node_helper
* @requires external:logger
*/
module.exports = NodeHelper.create({
/** @member {string} requiresVersion - Specifies minimum required version of MagicMirror². */
requiresVersion: '2.15.0',
/**
* @function providerExists
* @description Checks if the provider exists.
* @async
*
* @param {string} providerName - Name of the provider
*
* @returns {boolean} Does provider exist?
*/
async providerExists(providerName) {
try {
await fs.access(path.join(__dirname, 'apis', `${providerName}.js`));
return true;
} catch (e) {
return false;
}
},
/**
* @function socketNotificationReceived
* @description Receives socket notifications from the module.
* @async
* @override
*
* @param {string} notification - Notification name
* @param {*} payload - Detailed payload of the notification.
*
* @returns {void}
*/
async socketNotificationReceived(notification, payload) {
if (notification === 'CONFIG') {
this.config = payload;
const providerExists = await this.providerExists(this.config.provider);
if (providerExists) {
// eslint-disable-next-line global-require, import/no-dynamic-require
this.provider = await require(`./apis/${this.config.provider}`)(this.config);
this.getData();
setInterval(() => {
this.getData();
}, this.config.updateInterval);
} else {
Log.error(`${this.name}: Couldn't load provider ${this.config.provider}`);
}
}
},
/**
* @function getData
* @description Uses API provider to get data.
* @async
*
* @returns {void}
*/
async getData() {
try {
const data = await this.provider.getData();
this.sendSocketNotification('PRICELIST', data);
} catch (e) {
Log.error(`${this.name}: Failed to retrieve prices`, e);
}
}
});