feat: improve application access and money precision

This commit is contained in:
hectorzhao
2026-07-16 17:54:05 +08:00
parent 9d5c507007
commit faa716b8d0
49 changed files with 1699 additions and 489 deletions
+36
View File
@@ -0,0 +1,36 @@
import { BadRequestException } from '@nestjs/common';
export const MONEY_UNITS_PER_YUAN = 10_000;
export function moneyToNumber(value: number | bigint | null | undefined) {
if (value === null || value === undefined) return 0;
const result = typeof value === 'bigint' ? Number(value) : value;
if (!Number.isSafeInteger(result)) {
throw new RangeError('金额超过 JavaScript 安全整数范围');
}
return result;
}
export function moneyUnitsToYuan(value: number | bigint | null | undefined) {
return moneyToNumber(value) / MONEY_UNITS_PER_YUAN;
}
export function moneyUnitsToFixedYuan(value: number | bigint | null | undefined) {
return moneyUnitsToYuan(value).toFixed(4);
}
export function assertMoneyUnits(
value: number,
label: string,
options: { allowNegative?: boolean; allowZero?: boolean } = {},
) {
if (!Number.isSafeInteger(value)) {
throw new BadRequestException(`${label}最多支持人民币小数点后 4 位,且不能超过安全金额范围`);
}
if (!options.allowNegative && value < 0) {
throw new BadRequestException(`${label}不能为负数`);
}
if (options.allowZero === false && value === 0) {
throw new BadRequestException(`${label}不能为 0`);
}
}