Pour tout problème contactez-nous par mail : support@froggit.fr | La FAQ :grey_question: | Rejoignez-nous sur le Chat :speech_balloon:

Skip to content
Snippets Groups Projects
article-utils.js 2.06 KiB
Newer Older
peter_rabbit's avatar
peter_rabbit committed
"use strict";

const { fetchjson, fetchtext } = require("./fetch");

function getArticleBody(text) {
    return text.replaceAll("\n", "<br/>");
peter_rabbit's avatar
peter_rabbit committed
}

function getArticleDate(date) {
    return `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`;
}

function loadArticles(dir_url) {
    return new Promise((resolve, reject) => {
        fetchjson(`${dir_url}/index.json`)
            .then(json => {
                Promise.all(
peter_rabbit's avatar
peter_rabbit committed
                    json.articles.map(async artDir => {
                        const artPath = `${artDir}/${artDir}.json`;
                        const art = await fetchjson(`${dir_url}/${artPath}`);
                        const tmpSplit = artPath.split("/");
peter_rabbit's avatar
peter_rabbit committed
                        tmpSplit.pop();
                        const absArtPath = `${dir_url}/${tmpSplit.join("/")}`;
                        return Object.assign(art, { path: absArtPath });
                    })
                )
                    .then(articles => {
                        populateArticles(articles)
                            .then(completeArticles => resolve(completeArticles))
                            .catch(e => reject(e));
                    })
                    .catch(e => reject(e));
            })
            .catch(e => console.log(e));
    });
}

function populateArticles(articles) {
    return new Promise((resolve, reject) => {
        Promise.all(
            articles.map(async article => {
                if (article.body.indexOf("<file>") !== -1) {
                    const txtPath = article.body.replace("<file>", "");
                    const textValue = await fetchtext(`${article.path}/${txtPath}`);
                    article.body = textValue;
                    article.date = article.date ? new Date(article.date) : undefined;
                }
                return article;
            })
        )
            .then(completeArticles => resolve(completeArticles.sort((a, b) => b.date - a.date)))
peter_rabbit's avatar
peter_rabbit committed
            .catch(e => reject(e));
    });
}

module.exports = {
    loadArticles,
    getArticleBody,
    getArticleDate,
    populateArticles,
};