From af307b5888781ee3c488bcb6187218c5638d273f Mon Sep 17 00:00:00 2001 From: dbroqua Date: Fri, 31 Jan 2020 16:27:27 +0100 Subject: [PATCH] Fixed bug for parse JSON --- index.js | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index af69bbc..9dc367e 100644 --- a/index.js +++ b/index.js @@ -27,11 +27,12 @@ if (process.env.STREAM_PATH_ARTIST) { artistPath = process.env.STREAM_PATH_ARTIST.split('.') } -// Stockage du morceau en cours de lecture +// Sauvegarde temporaire du morceau en cours de lecture let currentSong = { artist: null, title: null } +// Sauvegarde des précédents morceaux (des 2 derniers à cause d'un bug sur Heavy1) const previousSongs = [ { artist: null, @@ -51,6 +52,31 @@ const bot = new irc.Client(process.env.IRC_SERVER, process.env.IRC_NICKNAME, { channels: [process.env.IRC_CHANNEL] }) +/** + * Fonction permettant d'extraire des infos depuis un objet JSON + * @param {Object} json + * @param {String} array + */ +const extractInfoFromJSON = (json, path) => { + let value = json + for (let i = 0; i < path.length; i += 1) { + if (path[i].indexOf('[') !== -1) { + const extractKeyIdex = path[i].split('[') + const key = extractKeyIdex[0] + const index = extractKeyIdex[1].replace(']', '') + + value = value[key][index] + } else { + value = value[path[i]] + } + } + + return value +} + +/** + * Fonction d'aficher le morceau en cours de lecture (et de le sauvegarder en base) + */ const displayCurrentSong = () => { // Just for debug console.info(`Now playing: ${currentSong.artist} - ${currentSong.title}`) @@ -111,14 +137,8 @@ if (!process.env.STREAM_TYPE || process.env.STREAM_TYPE === 'radio') { switch (process.env.STREAM_TYPE) { case 'json': - title = res[titlePath[0]] - for (let i = 1; i < titlePath.length; i += 1) { - title = title[titlePath[i]] - } - artist = res[artistPath[0]] - for (let i = 1; i < artistPath.length; i += 1) { - artist = artist[artistPath[i]] - } + title = extractInfoFromJSON(res, titlePath) + artist = extractInfoFromJSON(res, artistPath) currentSong = { title: title,