0
\$\begingroup\$

I'm refactoring a method for saving Stuff entities that belong to some Person. This is the current code:

async savePersonStuff(stuff, otherAttribute, personId) {
  const stuffWithPersonId = stuff.map(stuff => ({ ...stuff, personId }));
  const { sequelize } = this.stuffModel;
  const transaction = await sequelize.transaction({
    isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED,
  });

  await this.stuffModel.destroy({
    where: { personId }, transaction,
  });
  await this.personModel.update(
    { otherAttribute },
    { where: { id: personId } },
    { transaction });
  await this.stuffModel.bulkCreate(
    stuffWithPersonId, { transaction },
  );

  return transaction.commit();
}

Besides the obvious inneficiency of using destroy and bulkCreate (consuming the id sequence and fragmenting the index), this code doesn't feel like it's really using the ORM.

What can I do better with proper handling of model instances from Sequelize?

\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.