I'm using Faker in order to seed a database, I'm doing this using faker methods and lodash#random
.
Data generation is inside a loop, but on every execution is producing whole duplicates, how can I avoid it?
faker.locale = "es";
var leagueTeams = [{ "name" : "PerĂº","id" : "t834"},{"name" : "Venezuela","id" : "t833"},{"name" : "Argentina","id" : "t632"},{"name" : "Uruguay","id" : "t837"},{"name" : "Colombia","id" : "t832"},{"name" : "Bolivia","id" : "t836"},{"name" : "Jamaica","id" : "t1723"},{"name" : "Brazil","id" : "t614"},{"name" : "Mexico","id" : "t659"},{"name" : "Ecuador","id" : "t830"},{"name" : "Chile","id" : "t831"},{"name" : "Paraguay","id" : "t835"}]
for (var i = 0; i < 10; i++) {
var fakeName = faker.name.findName();
var fakeEmail = faker.internet.email();
var fakePassword = faker.internet.password();
var fakeTeam = faker.hacker.phrase();
var fakeTeamImage = faker.image.imageUrl();
var fakeFavoriteTeam = leagueTeams[_.random(0,11)];
var fakeBirthday = faker.date.past();
// Create account
request.post( {url:'http://localhost:1337/api/v1/auths/login',
form: {
email: fakeEmail,
password: fakePassword,
}
},
function (err, httpResponse, body) {
body = JSON.parse(body);
var iduser = body.user.id;
var auth = "Bearer " + body.token;
// Create team
request.put({
url: 'http://localhost:1337/api/v1/users/' + iduser,
form: {
name: fakeName,
gender: ['male','female'][i%2],
team: {name: fakeTeam, image: fakeTeamImage},
fanOf: {
name: fakeFavoriteTeam.name,
id: fakeFavoriteTeam.id
},
birthDate: fakeBirthday,
iduser: iduser
},
headers: {"Authorization": auth}
},
function (err, httpResponse, body) {
console.log(body);
}
);
});
}
So whole faker methods like faker.internet.findName()
, faker.hacker.phrase()
or the statement using lodash var fakeFavoriteTeam = leagueTeams[_.random(0,11)];
is always producing the same result, how could I improve it?
In JavaScript, The
var i
like statement withinfor
loop was declare as global variable, andrequest[method]
is not block code. It mean it continues change unless there is no block code inside loop.One way to declare local variable inside loop is using
let
(ES6 feature).Example of using
let
in loop with none block code.However you have to run node using the optional --harmony flag.
Using "strict" mode is because.
OR You can simplely use
Array.prototype.map()
orArray.prototype.forEach()