Last active
October 14, 2016 17:03
-
-
Save wharley/4afceb09529660fe0be67b9d87b9e23f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.upload = function(req, res){ | |
var form = new formidable.IncomingForm(); | |
form.parse(req, function(err, fields, files) { | |
readFile(files.file.path) | |
.then(processRows) | |
.then(processProducts) | |
.then(function(arrData){ | |
res.send({resposta: arrData}); | |
}) | |
}) | |
}; | |
function readFile(path) { | |
return new Promise(function(resolve, reject){ | |
fs.readFile(path, function(err, data){ | |
if(err) | |
return reject(err); | |
resolve(data); | |
}) | |
}) | |
} | |
function processRows(data){ | |
return new Promise(function(resolve, reject){ | |
var rows = encoding.convert(data.toString().split('\r\n'), 'utf8'); | |
var arrData = [] | |
rows.forEach(function(row){ | |
var arr = []; | |
arr.push(row.split(';')); | |
if( !isNaN(parseFloat(arr[0][0])) && isFinite(arr[0][0]) ){ | |
arrData.push({"code": arr[0][0], "product": 'Não cadastrado', "factory": arr[0][1], "price": arr[0][2]}) | |
} | |
}) | |
resolve(arrData) | |
}) | |
} | |
function processProducts(arrData){ | |
const codes = arrData.map(code => code) | |
const promises = codes.map(processProduct) | |
return Promise.all(promises) | |
} | |
function processProduct(code){ | |
return new Promise(function(resolve, reject){ | |
model.Produto.findAll({ | |
where: { | |
cod_produto: code.code | |
} | |
}).then(function(products){ | |
code.product = products[0] ? products[0].desc_produto : 'Não cadastrado' | |
resolve(code) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment