69 lines
2.9 KiB
JavaScript
69 lines
2.9 KiB
JavaScript
const chalk = require('chalk');
|
|
const nodeFetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
|
|
|
|
const utils = {
|
|
getDateString: () => {
|
|
let today = new Date();
|
|
let dateNow = today.toLocaleDateString();
|
|
|
|
return `${dateNow}`;
|
|
},
|
|
getTimeString: () => {
|
|
let today = new Date();
|
|
let timeNow = today.toLocaleTimeString();
|
|
|
|
return `${timeNow}`;
|
|
},
|
|
getDateTimeString: (delimiter = true) => {
|
|
let today = new Date();
|
|
let dateString = `${today.toLocaleDateString()} ${today.toLocaleTimeString()}`;
|
|
if (delimiter) {
|
|
dateString = `[${dateString}]`;
|
|
}
|
|
|
|
return dateString;
|
|
},
|
|
getDateTimeISOString: (delimiter = true) => {
|
|
let today = new Date();
|
|
let dateString = today.toISOString();
|
|
if (delimiter) {
|
|
dateString = `[${dateString}]`;
|
|
}
|
|
|
|
return dateString;
|
|
},
|
|
async fetchApi(price, next) {
|
|
let url = `${process.env.GOLDAPI_URL}/${price.metal}/${price.currency}`;
|
|
// url pour provoquer une erreur en dev : url = `https://www.goldapi.ioppppp/api/${price.metal}/${price.currency}`;
|
|
let options = {
|
|
method: 'GET',
|
|
headers: {
|
|
'x-access-token': process.env.GOLDAPI_TOKEN,
|
|
'Content-Type': 'application/json'
|
|
},
|
|
redirect: 'follow'
|
|
};
|
|
try {
|
|
// Pour tester le retour d'erreur : return { errors: { name: 'error name', message: 'error message', type: 'TYPE', code: 'CODE' } };
|
|
const response = await nodeFetch(url, options);
|
|
if (response.status >= 200 && response.status < 400) {
|
|
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${price.metal} | ${price.currency} - Réception du prix spot via API`), chalk.magenta(price.price), `${response.status} ${response.statusText}`);
|
|
price = response.json();
|
|
price.then(values => {
|
|
values.timestamp *= 1000;
|
|
return values;
|
|
});
|
|
} else {
|
|
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - Erreur ${response.status} ${response.statusText} - Réutilisation du prix stocké`), chalk.magenta(price.price));
|
|
price = { errors: { name: response.statusText, message: `Une erreur ${response.status} '${response.statusText}' est survenue lors de la récupération des prix spots`, type: 'API Error', code: response.status } };
|
|
}
|
|
return price;
|
|
} catch (error) {
|
|
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - fetchApi error`));
|
|
return { errors: { name: error.name, message: error.message, type: error.type, code: error.code } };
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = utils;
|