Skip to content

Commit

Permalink
reworded seeders
Browse files Browse the repository at this point in the history
  • Loading branch information
rocambille committed Feb 17, 2024
1 parent 8e5b378 commit 44be95f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 10 deletions.
18 changes: 10 additions & 8 deletions template/server/database/fixtures/AbstractSeeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,29 @@ class AbstractSeeder {
this.refs = refs;
}

async #doSave(data, name) {
async #doInsert(data) {
const { refName, ...values } = data;

// Prepare the SQL statement: "insert into <table>(<fields>) values (<placeholders>)"
const fields = Object.keys(data).join(",");
const placeholders = new Array(Object.keys(data).length)
const fields = Object.keys(values).join(",");
const placeholders = new Array(Object.keys(values).length)
.fill("?")
.join(",");

const sql = `insert into ${this.table}(${fields}) values (${placeholders})`;

// Perform the query and if applicable store the insert id given the ref
const [result] = await database.query(sql, Object.values(data));
const [result] = await database.query(sql, Object.values(values));

if (name != null) {
if (refName != null) {
const { insertId } = result;

refs[name] = { ...data, insertId };
refs[refName] = { ...values, insertId };
}
}

save(data, name) {
this.promises.push(this.#doSave(data, name));
insert(data) {
this.promises.push(this.#doInsert(data));
}

// eslint-disable-next-line class-methods-use-this
Expand Down
2 changes: 1 addition & 1 deletion template/server/database/fixtures/ItemSeeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ItemSeeder extends AbstractSeeder {
user_id: this.getRef(`user_${i}`).insertId,
};

this.save(fakeItem); // insert into item(title, user_id) values (?, ?)
this.insert(fakeItem); // insert into item(title, user_id) values (?, ?)
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion template/server/database/fixtures/UserSeeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ class UserSeeder extends AbstractSeeder {
const fakeUser = {
email: this.faker.internet.email(),
password: this.faker.internet.password(),
refName: `user_${i}`,
};

this.save(fakeUser, `user_${i}`); // `user_${i}` = insert into user(email, password) values (?, ?)
this.insert(fakeUser); // insert into user(email, password) values (?, ?)
}
}
}
Expand Down

0 comments on commit 44be95f

Please sign in to comment.