{"size": 1913, "ext": "js", "max_stars_repo_path": "fetch-free-games.js", "max_stars_repo_name": "fbrossar25/Free-Games-Bot", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fetch-free-games.js", "max_issues_repo_name": "fbrossar25/Free-Games-Bot", "max_issues_repo_issues_event_min_datetime": "2020-09-17T07:17:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-16T16:28:45.000Z", "max_forks_repo_path": "fetch-free-games.js", "max_forks_repo_name": "fbrossar25/Free-Games-Bot", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 3, "max_forks_count": null, "avg_line_length": 31.3606557377, "max_line_length": 96, "alphanum_fraction": 0.5007841087}
const Utils = require('./utils');
const { epicStore, humbleBundleStore, gogStore } = require('./stores');
const stores = {
    'epic': epicStore,
    'humble': humbleBundleStore,
    'gog': gogStore,
};
const knownSources = Object.keys(stores);

function unique(value, index, self) {
    return self.indexOf(value) === index;
}

function formatSources(sources) {
    const usableSources = Array.isArray(sources) && sources.length > 0 ? sources : knownSources;
    return usableSources.map(s => s.trim().toLowerCase()).filter(unique);
}

module.exports.knownSources = knownSources;

module.exports.fetch = (sources) => {
    return new Promise((success) => {
        const fetchPromises = [];

        // Preparing calls to each stores
        formatSources(sources).forEach(source => {
            if(source in stores) {
                fetchPromises.push(stores[source].fetch());
            }
            else {
                fetchPromises.push({
                    source:source,
                    error: `Unknown source named '${source}'`,
                });
            }
        });
        // Merging each stores reponses
        Promise.allSettled(fetchPromises).then((fetchResults) => {
            const result = {
                games: [],
                errors: [],
            };
            for(const fetchResult of fetchResults) {
                const value = fetchResult.value;
                if(value.error) {
                    result.errors.push({
                        source: value.source,
                        message: value.error,
                    });
                }
                else {
                    for(const game of value.games) {
                        result.games.push(game);
                    }
                }
            }
            Utils.log(`Free games found : ${JSON.stringify(result)}`);
            success(result);
        });
    });
};