Skip to content

Instantly share code, notes, and snippets.

@alphamikle

alphamikle/tewtutin_4.ts

Last active Feb 11, 2021
Embed
What would you like to do?
// ...
async makeRemittance(fromId: number, toId: number, sum: number, withError = false, transaction = true): Promise<RemittanceResultDto> {
const fromUser = await this.userRepository.findOne(fromId, { transaction });
const toUser = await this.userRepository.findOne(toId, { transaction });
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 this.purseRepository.findOne(fromUser.defaultPurseId, { transaction });
const toPurse = await this.purseRepository.findOne(toUser.defaultPurseId, { transaction });
const modalSum = Math.abs(sum);
if (fromPurse.balance < modalSum) {
throw new Error(NOT_ENOUGH_MONEY(fromId));
}
fromPurse.balance -= sum;
toPurse.balance += sum;
await this.purseRepository.save(fromPurse, { transaction });
if (withError) {
throw new Error('Unexpectable error was thrown while remittance');
}
await this.purseRepository.save(toPurse, { transaction });
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