Skip to content

Instantly share code, notes, and snippets.

@danielfttorres
Created November 18, 2015 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielfttorres/93b3e4945b42087027c4 to your computer and use it in GitHub Desktop.
Save danielfttorres/93b3e4945b42087027c4 to your computer and use it in GitHub Desktop.
db.search(query, params, function(err, data) { // Busca de Vinyls na API Externa.
var discogsVinyls = data.results.map(function(item) { // `map` para selecionar as propriedades que quero.
var item = {
slug: slug(item.title).toLowerCase(),
discogsId: item.id,
cover: item.thumb || null,
title: item.title,
artists: item.artists || null,
genre: item.genre,
year: item.year,
country: item.contry || null,
label: item.label || null
};
return item;
});
var arr = []; // Array que será retornado no final. Ex.: `res.json(arr)`.
var itemNum = []; // Array utilizado para fazer a contagem que determinará o final.
for (var i = 0; i < discogsVinyls.length; i++) {
_this.VinylsModel.findOneAsync({ slug: discogsVinyls[i].slug }) // Checa se o Vinyl já existe no meu DB através do `slug`.
.then(function(vinyl) {
if(vinyl) { // Não quero Vinyls repetidos.
if(vinyl.discogsId == discogsVinyls[this].discogsId) { // Checagem novamente pelo `discogsId`.
itemNum.push(this); // Incrementa +1 em `itemNum`.
} else {
itemNum.push(this); // Incrementa +1 em `itemNum`.
arr.push(discogsVinyls[this]); // Adicionar o Vinyl na array `arr`.
_this.VinylsModel.insertAsync(discogsVinyls[this]) // Adicionar o Vinyl no DB.
}
} else {
itemNum.push(this); // Incrementa +1 em `itemNum`.
arr.push(discogsVinyls[this]); // Adicionar o Vinyl na array `arr`.
_this.VinylsModel.insertAsync(discogsVinyls[this]) // Adicionar o Vinyl no DB.
}
if(itemNum.length === discogsVinyls.length) {
res.json(arr); // FINAL: retorna um JSON com os discos. `res.json` só pode ser usado uma vez, por isso está no final.
}
}.bind(i));
}; // Fim do for.
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment