Skip to content

Instantly share code, notes, and snippets.

@alphamikle
Last active February 11, 2021 18:41
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 alphamikle/84e224852bd06d6189d16204a4086c66 to your computer and use it in GitHub Desktop.
Save alphamikle/84e224852bd06d6189d16204a4086c66 to your computer and use it in GitHub Desktop.
async makeRemittanceWithTypeOrmV1(transactionEntityManager: EntityManager, fromId: number, toId: number, sum: number, withError = false) {
const fromUser = await transactionEntityManager.findOne(User, fromId); // <-- we need to use only provided transactionEntityManager, for make all requests in transaction
const toUser = await transactionEntityManager.findOne(User, toId); // <-- and there
if (fromUser === undefined) {
throw new Error(NOT_FOUND_USER_WITH_ID(fromId));
}
if (toUser === undefined) {
throw new Error(NOT_FOUND_USER_WITH_ID(toId));
}
if (fromUser.defaultPurseId === null) {
throw new Error(USER_DOES_NOT_HAVE_PURSE(fromId));
}
if (toUser.defaultPurseId === null) {
throw new Error(USER_DOES_NOT_HAVE_PURSE(toId));
}
const fromPurse = await transactionEntityManager.findOne(Purse, fromUser.defaultPurseId); // <-- there
const toPurse = await transactionEntityManager.findOne(Purse, toUser.defaultPurseId); // <--there
const modalSum = Math.abs(sum);
if (fromPurse.balance < modalSum) {
throw new Error(NOT_ENOUGH_MONEY(fromId));
}
fromPurse.balance -= sum;
toPurse.balance += sum;
await this.appServiceV2.savePurse(fromPurse); // <-- oops, something was wrong
if (withError) {
throw new Error('Unexpectable error was thrown while remittance');
}
await transactionEntityManager.save(toPurse);
const remittance = new RemittanceResultDto();
remittance.fromId = fromId;
remittance.toId = toId;
remittance.fromBalance = fromPurse.balance;
remittance.sum = sum;
return remittance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment