Source: service/StructService.js

'use strict';

/**
 * @module Services
 * Plain functionality in service methods.
 * @license MIT
 * @author Kai KRETSCHMANN <kai@kretschmann.consulting>
 */

const log4js = require("log4js");
const logger = log4js.getLogger();
logger.level = process.env.LOGLEVEL || "warn";

const Atomic = require("./AtomicService");


/**
 * @method
 * Get structure of atomic elements
 * @public
 *
 * @param {int} amount - Integer positive whole number of words
 * @param {array} format - Array of format entries
 * @returns Array of structures
 **/
exports.getStructure = function(amount, format) {
    return new Promise(function(resolve, reject) {
        if (amount <= 0) {
            logger.error("amount to small");
            reject("amount must be positive");
        }

        let promises = [];
        for (const entry of format) {
            switch (entry.paramType) {
                case "number":
                    const iFrom = Number(entry.paramFrom);
                    const iTo = Number(entry.paramTo);
                    promises.push(Atomic.getRandomNumbers(amount, iFrom, iTo));
                    break;
                case "loremipsum":
                    promises.push(Atomic.getLoremIpsum(amount));
                    break;
                case "processname":
                    promises.push(Atomic.getProcessNames(amount));
                    break;
                case "isbn":
                    promises.push(Atomic.getIsbn(amount));
                    break;
                case "uuid":
                    promises.push(Atomic.getUuid(amount));
                    break;
                case "phone":
                    promises.push(Atomic.getPhone(amount));
                    break;
                case "timestamp":
                    const sFrom = entry.paramFrom;
                    const sTo = entry.paramTo;
                    promises.push(Atomic.getTimestamp(amount, sFrom, sTo));
                    break;
            } // switch
        } // for

        Promise.all(promises)
            .then(function(data) {
                let aStructArray = [];
                for (let i = 0; i < amount; i++) {
                    let oEntry = {};
                    let j = 0;
                    for (const f of format) {
                        let p = f.paramName;
                        oEntry[p] = data[j][i];
                        j += 1;
                    }
                    aStructArray.push(oEntry);
                }
                resolve(aStructArray);
            })
            .catch(function(err) {
                reject(err);
            });
    });
}