eslint, prettier fix

This commit is contained in:
Данил 2024-08-17 16:40:20 +03:00
parent bdc4450b72
commit 2679fa20d5
10 changed files with 284 additions and 208 deletions

View file

@ -13,13 +13,16 @@ const logger = require('../shared/logger/src/main.js');
* @returns {Promise<Error|string>} * @returns {Promise<Error|string>}
*/ */
async function gen_chart(from_currency, conv_currency, start_date, end_date) { async function gen_chart(from_currency, conv_currency, start_date, end_date) {
const data = await pool.query('SELECT date, rate FROM currency WHERE ' + const data = await pool.query(
'(date BETWEEN $3 AND $4) AND from_currency = $1 AND conv_currency = $2 ORDER BY date ', [ 'SELECT date, rate FROM currency WHERE ' +
'(date BETWEEN $3 AND $4) AND from_currency = $1 AND conv_currency = $2 ORDER BY date ',
[
from_currency.toUpperCase(), from_currency.toUpperCase(),
conv_currency.toUpperCase(), conv_currency.toUpperCase(),
start_date, start_date,
end_date end_date,
]); ],
);
if (!data['rows'][0]) return 'Missing data'; if (!data['rows'][0]) return 'Missing data';
@ -31,7 +34,8 @@ async function gen_chart(from_currency, conv_currency, start_date, end_date) {
rate.push(data.rows[i].rate); rate.push(data.rows[i].rate);
} }
const chart = ChartJSImage().chart({ const chart = ChartJSImage()
.chart({
type: 'line', type: 'line',
options: { options: {
title: { title: {
@ -44,18 +48,24 @@ async function gen_chart(from_currency, conv_currency, start_date, end_date) {
{ {
ticks: { ticks: {
beginAtZero: false, beginAtZero: false,
} },
} },
] ],
} },
] ],
}, },
data: { data: {
labels: date, labels: date,
datasets: [ datasets: [
{ {
borderColor: rate[0] < rate[rate.length-1] ? 'rgb(24, 218, 39)' : 'rgb(243, 85, 50)', borderColor:
backgroundColor: rate[0] < rate[rate.length-1] ? 'rgb(36, 175, 47)' : 'rgb(218, 56, 24)', rate[0] < rate[rate.length - 1]
? 'rgb(24, 218, 39)'
: 'rgb(243, 85, 50)',
backgroundColor:
rate[0] < rate[rate.length - 1]
? 'rgb(36, 175, 47)'
: 'rgb(218, 56, 24)',
data: rate, data: rate,
borderWidth: 2, borderWidth: 2,
}, },
@ -66,7 +76,7 @@ async function gen_chart(from_currency, conv_currency, start_date, end_date) {
{ {
scaleLabel: { scaleLabel: {
display: true, display: true,
labelString: 'Day' labelString: 'Day',
}, },
}, },
], ],
@ -75,19 +85,20 @@ async function gen_chart(from_currency, conv_currency, start_date, end_date) {
stacked: false, stacked: false,
scaleLabel: { scaleLabel: {
display: true, display: true,
labelString: 'Rate' labelString: 'Rate',
}, },
}, },
], ],
}, },
}).width(1000).height(1000); })
.width(1000)
.height(1000);
logger.debug(chart.toURL()); logger.debug(chart.toURL());
return chart.toURL(); return chart.toURL();
} }
/** /**
* Saving a graph to a file * Saving a graph to a file
* @param {String} url - URL (or Buffer) to the chart * @param {String} url - URL (or Buffer) to the chart
@ -95,17 +106,20 @@ async function gen_chart(from_currency, conv_currency, start_date, end_date) {
*/ */
function save_chart(url, filename) { function save_chart(url, filename) {
if (!fs.existsSync('../charts')) fs.mkdirSync('../charts'); if (!fs.existsSync('../charts')) fs.mkdirSync('../charts');
if (!url.startsWith('https://')) throw new Error('The passed parameter is not a URL'); if (!url.startsWith('https://'))
throw new Error('The passed parameter is not a URL');
logger.info(`The schedule has been saved. The path of the graph 'chart/${filename}'`); logger.info(
axios({url, responseType: 'stream',}).then( `The schedule has been saved. The path of the graph 'chart/${filename}'`,
response => );
axios({ url, responseType: 'stream' }).then(
(response) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
response.data response.data
.pipe(fs.createWriteStream(`../charts/${filename}`)) .pipe(fs.createWriteStream(`../charts/${filename}`))
.on('finish', () => resolve()) .on('finish', () => resolve())
.on('error', e => reject(e)); .on('error', (e) => reject(e));
}) }),
); );
} }

View file

@ -12,7 +12,8 @@ function main() {
for (const file of files) { for (const file of files) {
try { try {
const fileSize = fs.statSync(`../charts/${file}`)['size'] / 1024; const fileSize =
fs.statSync(`../charts/${file}`)['size'] / 1024;
folderSize += fileSize; folderSize += fileSize;
if (folderSize > config['currency']['chart']['max_size']) { if (folderSize > config['currency']['chart']['max_size']) {
@ -20,7 +21,9 @@ function main() {
fs.unlinkSync(`../charts/${files[i]}`); fs.unlinkSync(`../charts/${files[i]}`);
} }
} }
} catch { return; } } catch {
return;
}
} }
}); });
} }

View file

@ -8,7 +8,8 @@ const save_crypto = require('./save_crypto');
async function main() { async function main() {
const config_schedule = config['currency']['collecting']['schedule']; const config_schedule = config['currency']['collecting']['schedule'];
if (!config_schedule) throw new Error('The crontab schedule is not set'); if (!config_schedule) throw new Error('The crontab schedule is not set');
if (!cron.isValidCron(config_schedule, {alias: true})) throw new Error('The crontab is invalid'); if (!cron.isValidCron(config_schedule, { alias: true }))
throw new Error('The crontab is invalid');
await save_fiat(); await save_fiat();
await save_crypto(); await save_crypto();

View file

@ -17,44 +17,54 @@ function save_crypto() {
return; return;
} }
logger.info(`Active coinapi key: ${coinapiKeys[apiKeyIndex]} (${coinapiKeys.length-1} / ${apiKeyIndex})`); logger.info(
`Active coinapi key: ${coinapiKeys[apiKeyIndex]} (${coinapiKeys.length - 1} / ${apiKeyIndex})`,
);
config['currency']['crypto'].forEach( config['currency']['crypto'].forEach((value) =>
(value) => config['currency']['crypto'].forEach((pair) => { config['currency']['crypto'].forEach((pair) => {
if (value === pair) return; if (value === pair) return;
axios.get(`https://rest.coinapi.io/v1/exchangerate/${value}/${pair}`, axios
.get(
`https://rest.coinapi.io/v1/exchangerate/${value}/${pair}`,
{ {
timeout: 3000, timeout: 3000,
headers: { headers: {
'X-CoinAPI-Key': coinapiKeys[apiKeyIndex], 'X-CoinAPI-Key': coinapiKeys[apiKeyIndex],
} },
}).then(async (res) => { },
)
.then(async (res) => {
const data = res.data; const data = res.data;
const point = data['rate'].toString().indexOf('.') + 4; const point = data['rate'].toString().indexOf('.') + 4;
logger.debug(JSON.stringify(data)); logger.debug(JSON.stringify(data));
const db = await pool.query('SELECT * FROM currency WHERE from_currency = $1 AND conv_currency = $2 AND date = $3', const db = await pool.query(
'SELECT * FROM currency WHERE from_currency = $1 AND conv_currency = $2 AND date = $3',
[ [
value, value,
pair, pair,
new Date(data['time']).toLocaleDateString() new Date(data['time']).toLocaleDateString(),
]); ],
);
if (db['rows'][0]) return; if (db['rows'][0]) return;
await pool.query(`INSERT INTO currency (from_currency, conv_currency, rate, date) await pool.query(
`INSERT INTO currency (from_currency, conv_currency, rate, date)
VALUES ($1, $2, $3, $4)`, VALUES ($1, $2, $3, $4)`,
[ [
value, value,
pair, pair,
data['rate'].toString().slice(0, point), data['rate'].toString().slice(0, point),
new Date(data['time']).toLocaleDateString() new Date(data['time']).toLocaleDateString(),
]); ],
);
}).catch((err) => { })
if (err.response?.data.detail) logger.error(err.response.data.detail); .catch((err) => {
if (err.response?.data.detail)
logger.error(err.response.data.detail);
if (err.response?.data.status === 429) { if (err.response?.data.status === 429) {
logger.info('CoinAPI rate limited, rotating token'); logger.info('CoinAPI rate limited, rotating token');
rotate_key(coinapiKeys); rotate_key(coinapiKeys);
@ -62,7 +72,7 @@ function save_crypto() {
save_crypto(); save_crypto();
} }
}); });
}) }),
); );
} }

View file

@ -10,42 +10,56 @@ const logger = require('../shared/logger/src/main.js');
async function save_fiat() { async function save_fiat() {
if (!config['currency']['collecting']['fiat']) return; if (!config['currency']['collecting']['fiat']) return;
config['currency']['fiat'].forEach( config['currency']['fiat'].forEach((value) =>
(value) => config['currency']['fiat'].forEach(async (pair) => { config['currency']['fiat'].forEach(async (pair) => {
if (value === pair) return; if (value === pair) return;
await axios.get( await axios
.get(
`https://duckduckgo.com/js/spice/currency/1/${value}/${pair}`, `https://duckduckgo.com/js/spice/currency/1/${value}/${pair}`,
{ {
timeout: 3000, timeout: 3000,
}).then(async (res) => { },
)
.then(async (res) => {
const regExp = new RegExp('\\(\\s*(.*)\\s*\\);$', 'mg'); const regExp = new RegExp('\\(\\s*(.*)\\s*\\);$', 'mg');
const data = JSON.parse(Array.from(res.data.matchAll(regExp))[0][1]); const data = JSON.parse(
Array.from(res.data.matchAll(regExp))[0][1],
);
delete data['terms']; delete data['terms'];
delete data['privacy']; delete data['privacy'];
logger.debug(JSON.stringify(data)); logger.debug(JSON.stringify(data));
const point = data['to'][0]['mid'].toString().indexOf('.') + 4; const point =
data['to'][0]['mid'].toString().indexOf('.') + 4;
const db = await pool.query('SELECT * FROM currency WHERE ' + const db = await pool.query(
'SELECT * FROM currency WHERE ' +
'from_currency = $1 AND conv_currency = $2 AND date = $3', 'from_currency = $1 AND conv_currency = $2 AND date = $3',
[ value, pair, new Date(data['timestamp']).toLocaleDateString() ]); [
value,
pair,
new Date(data['timestamp']).toLocaleDateString(),
],
);
if (db['rows'][0]) return; if (db['rows'][0]) return;
await pool.query(`INSERT INTO currency (from_currency, conv_currency, rate, date) VALUES ($1, $2, $3, $4)`, await pool.query(
`INSERT INTO currency (from_currency, conv_currency, rate, date) VALUES ($1, $2, $3, $4)`,
[ [
value, value,
pair, pair,
data['to'][0]['mid'].toString().slice(0, point), data['to'][0]['mid'].toString().slice(0, point),
new Date(data['timestamp']).toLocaleDateString() new Date(data['timestamp']).toLocaleDateString(),
]); ],
}).catch((err) => { );
})
.catch((err) => {
logger.error(err); logger.error(err);
setTimeout(save_fiat, err.config.timeout); setTimeout(save_fiat, err.config.timeout);
}); });
}),
})
); );
} }

View file

@ -4,12 +4,20 @@ const fs = require('fs');
const fastify = require('fastify')({ const fastify = require('fastify')({
logger: config['server']['log']['print'] ? logger : false, logger: config['server']['log']['print'] ? logger : false,
...config['server']['ssl']['work'] ? { ...(config['server']['ssl']['work']
? {
https: { https: {
key: fs.readFileSync(config['server']['ssl']['private_key'], 'utf8'), key: fs.readFileSync(
cert: fs.readFileSync(config['server']['ssl']['cert'], 'utf8'), config['server']['ssl']['private_key'],
'utf8',
),
cert: fs.readFileSync(
config['server']['ssl']['cert'],
'utf8',
),
},
} }
} : false : false),
}); });
const rate = require('../shared/database/src/main.js'); const rate = require('../shared/database/src/main.js');
@ -20,23 +28,30 @@ fastify.get('/api/getRate/', async function (req, res){
if (!query['from_currency'] || !query['conv_currency']) { if (!query['from_currency'] || !query['conv_currency']) {
return res.status(400).send({ return res.status(400).send({
status: 400, status: 400,
message: 'The from_currency and conv_currency fields are required' message: 'The from_currency and conv_currency fields are required',
}); });
} }
if (query['date'])
if (query['date']) return rate.getDay(query['from_currency'], query['conv_currency'], query['date']); return rate.getDay(
else if (query['start_date'] && query['end_date']) return rate.getPeriod( query['from_currency'],
query['conv_currency'],
query['date'],
);
else if (query['start_date'] && query['end_date'])
return rate.getPeriod(
query['from_currency'], query['from_currency'],
query['conv_currency'], query['conv_currency'],
query['start_date'], query['start_date'],
query['end_date'] query['end_date'],
); );
else return res.status(400).send({ else
return res.status(400).send({
status: 400, status: 400,
message: 'The date or period field is incorrect. ' + message:
'There must be fields \'date\' or \'start_date\' and \'end_date\'. ' + 'The date or period field is incorrect. ' +
'Read more in the documentation' "There must be fields 'date' or 'start_date' and 'end_date'. " +
'Read more in the documentation',
}); });
}); });
@ -48,7 +63,8 @@ fastify.get('/api/getChart/', async function (req, res){
message: 'The from_currency and conv_currency fields are required', message: 'The from_currency and conv_currency fields are required',
}); });
} }
if (!query['start_date'] || !query['end_date']) return res.status(400).send({ if (!query['start_date'] || !query['end_date'])
return res.status(400).send({
status: 400, status: 400,
message: 'start_date and end_date is required', message: 'start_date and end_date is required',
}); });
@ -60,10 +76,11 @@ fastify.get('/api/getChart/', async function (req, res){
query['end_date'], query['end_date'],
); );
if (config['currency']['chart']['save']) chart.save_chart( if (config['currency']['chart']['save'])
chart.save_chart(
charts, charts,
`${query['from_currency']} ${query['conv_currency']} ` + `${query['from_currency']} ${query['conv_currency']} ` +
`(${query['start_date']} - ${query['end_date']}).png` `(${query['start_date']} - ${query['end_date']}).png`,
); );
return res.status(200).send({ return res.status(200).send({
@ -72,12 +89,15 @@ fastify.get('/api/getChart/', async function (req, res){
}); });
}); });
fastify.listen({ fastify.listen(
{
port: 3000, port: 3000,
host: config['server']['host'] ? config['server']['host'] : 'localhost', host: config['server']['host'] ? config['server']['host'] : 'localhost',
}, (err) => { },
(err) => {
if (err) { if (err) {
fastify.log.error(err); fastify.log.error(err);
process.exit(1); process.exit(1);
} }
}); },
);

View file

@ -7,5 +7,4 @@ const config = () => {
return yaml.parse(fs.readFileSync('../config.yaml', 'utf-8')); return yaml.parse(fs.readFileSync('../config.yaml', 'utf-8'));
}; };
module.exports = config; module.exports = config;

View file

@ -10,20 +10,22 @@ const logger = require('../../logger/src/main.js');
*/ */
async function getDay(from_currency, conv_currency, date) { async function getDay(from_currency, conv_currency, date) {
if (!from_currency || !conv_currency) return new Error('fromCurrency and convCurrency are required'); if (!from_currency || !conv_currency)
return new Error('fromCurrency and convCurrency are required');
else if (!date) return new Error('date is required'); else if (!date) return new Error('date is required');
const data = await pool.query('SELECT from_currency, conv_currency, date, rate FROM currency ' + const data = await pool.query(
'WHERE from_currency = $1 AND conv_currency = $2 AND date = $3', [ 'SELECT from_currency, conv_currency, date, rate FROM currency ' +
from_currency.toUpperCase(), 'WHERE from_currency = $1 AND conv_currency = $2 AND date = $3',
conv_currency.toUpperCase(), [from_currency.toUpperCase(), conv_currency.toUpperCase(), date],
date );
]);
if (!data) return new Error('Missing data'); if (!data) return new Error('Missing data');
const set_date = data['rows'][0]['date']; const set_date = data['rows'][0]['date'];
data['rows'][0]['date'] = new Date(set_date.setDate(set_date.getDate() + 1)); data['rows'][0]['date'] = new Date(
set_date.setDate(set_date.getDate() + 1),
);
logger.debug(data['rows'][0]); logger.debug(data['rows'][0]);
@ -40,16 +42,21 @@ async function getDay(from_currency, conv_currency, date) {
*/ */
async function getPeriod(from_currency, conv_currency, start_date, end_date) { async function getPeriod(from_currency, conv_currency, start_date, end_date) {
if (!from_currency || !conv_currency) return new Error('from_currency and conv_currency are required'); if (!from_currency || !conv_currency)
else if(!start_date || !end_date) return new Error('start_date and end_date are required'); return new Error('from_currency and conv_currency are required');
else if (!start_date || !end_date)
return new Error('start_date and end_date are required');
const data = await pool.query('SELECT * FROM currency WHERE ' + const data = await pool.query(
'(date BETWEEN $3 AND $4) AND from_currency = $1 AND conv_currency = $2 ORDER BY date', [ 'SELECT * FROM currency WHERE ' +
'(date BETWEEN $3 AND $4) AND from_currency = $1 AND conv_currency = $2 ORDER BY date',
[
from_currency.toUpperCase(), from_currency.toUpperCase(),
conv_currency.toUpperCase(), conv_currency.toUpperCase(),
start_date, start_date,
end_date end_date,
]); ],
);
if (!data) return new Error('Missing data'); if (!data) return new Error('Missing data');

View file

@ -1,13 +1,12 @@
const pg = require("pg"); const pg = require('pg');
const config = require("../../config/src/main.js")(); const config = require('../../config/src/main.js')();
const pool = new pg.Pool({ const pool = new pg.Pool({
user: config['database']['user'], user: config['database']['user'],
password: config['database']['password'], password: config['database']['password'],
host: config['database']['host'], host: config['database']['host'],
port: config['database']['port'], port: config['database']['port'],
database: config['database']['name'] database: config['database']['name'],
}); });
module.exports = pool; module.exports = pool;

View file

@ -11,37 +11,46 @@ function getCallerFile() {
const err = new Error(); const err = new Error();
let currentFile; let currentFile;
Error.prepareStackTrace = function (err, stack) { return stack; }; Error.prepareStackTrace = function (err, stack) {
return stack;
};
currentFile = err.stack.shift().getFileName(); currentFile = err.stack.shift().getFileName();
while (err.stack.length) { while (err.stack.length) {
callerFile = err.stack.shift().getFileName(); callerFile = err.stack.shift().getFileName();
if (currentFile !== callerFile) break; if (currentFile !== callerFile) break;
} }
} catch { return; } } catch {
return;
}
Error.prepareStackTrace = originalFunc; Error.prepareStackTrace = originalFunc;
return callerFile ? path.basename(callerFile) : 'unknown'; return callerFile ? path.basename(callerFile) : 'unknown';
} }
const logger = pino({ const logger = pino(
level: config['server']['log']['level'] ? config['server']['log']['level'] : 'info', {
level: config['server']['log']['level']
? config['server']['log']['level']
: 'info',
prettifier: pretty, prettifier: pretty,
prettify: true, prettify: true,
messageKey: 'msg', messageKey: 'msg',
timestampKey: 'time', timestampKey: 'time',
}, pretty({ },
pretty({
ignore: 'pid,hostname', ignore: 'pid,hostname',
messageFormat: '{msg}', messageFormat: '{msg}',
})); }),
);
function wrapLogger(logger) { function wrapLogger(logger) {
const levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace']; const levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];
const wrappedLogger = {}; const wrappedLogger = {};
levels.forEach(level => { levels.forEach((level) => {
wrappedLogger[level] = function (msg, ...args) { wrappedLogger[level] = function (msg, ...args) {
const callerFile = getCallerFile(); const callerFile = getCallerFile();
const msgWithFilename = `[${callerFile}] ${msg}`; const msgWithFilename = `[${callerFile}] ${msg}`;