tramonrails
9/4/2019 - 11:31 AM

smartyAds.js

const http = require("http")
const url = require("url")

const server = http.createServer().listen(3000, () => console.log('Server listening on port 3000'))

server.on("request", (req, res) => {
    const urlParsed = url.parse(req.url, true)

    if (req.method === "POST" && urlParsed.pathname === "/testing-rout") {
        if (urlParsed.query.test === "1") {
            handler(req, res, true)
        } else {
            handler(req, res, false)
        }
    }

})

const handler = (req, res, isWithQuery) => {
    let body = ""
    req.on("data", chunk => {
        body += chunk
    })
    req.on("end", () => {
        const arr = []
        for (let i = 2; i <= 6; i++) {
            arr.push(multiply(JSON.parse(body), i, isWithQuery))
        }
        res.setHeader("Content-Type", "application/json")
        res.end(JSON.stringify(arr))
    })
}

const multiply = (obj, factor, isWithQuery) => {
    for (let i in obj) {
        if (!obj.hasOwnProperty(i)) {
            continue
        }
        if (typeof obj[i] === "object") {
            multiply(obj[i], factor, isWithQuery)
        } else if (!isNaN(obj[i])) {
            if (isWithQuery) {
                let multiplied = (parseFloat(obj[i]) * 2) * factor
                obj[i] = +multiplied.toFixed(2)
            } else {
                let multiplied = (parseFloat(obj[i]) + 1) * factor
                obj[i] = +multiplied.toFixed(2)
            }

        }
    }
    return obj
}