NestJs中使用npm库mathjs遇报错,自定义装饰器求助
解决NestJS自定义装饰器中mathjs调用报错的问题
错误原因分析
你遇到的TypeError: Cannot read properties of undefined (reading 'unit')本质是math对象未被正确导入,导致调用math.unit时触发未定义错误。这是因为mathjs的ES模块导出规则并非默认导出整个math实例,而是需要通过命名空间导入的方式获取完整对象。
简化解决方案(无需自定义提供者)
只需要两步就能解决:
1. 修正mathjs的导入语句
将原导入方式:
import math from 'mathjs';
替换为:
import * as math from 'mathjs';
这会完整导入mathjs的所有功能模块,确保math.unit等方法能被正常访问。
2. 完善计量单位验证逻辑
原代码只是打印测试,我们可以利用mathjs的API实现真实的验证:通过尝试创建单位实例,捕获异常来判断字符串是否为有效计量单位。
修改后的完整装饰器代码:
import { ValidationArguments, registerDecorator } from 'class-validator'; import * as math from 'mathjs'; export function IsMeasurementUnit() { return function (object: Object, propertyName: string) { registerDecorator({ name: 'isMeasurementUnit', target: object.constructor, propertyName: propertyName, constraints: [], options: { message: 'Text must be a valid unit of measurement' }, validator: { validate(value: any, args: ValidationArguments) { // 先排除非字符串类型 if (typeof value !== 'string') return false; try { // 尝试创建单位实例,验证有效性 math.unit(1, value); return true; } catch (error) { return false; } }, }, }); }; }
补充说明
如果你的mathjs版本支持math.isUnit方法,也可以直接用return math.isUnit(value)替代try-catch逻辑,代码会更简洁。这个方案完全不需要自定义提供者,只是修正了第三方库的导入方式和验证逻辑,符合你想要的简便需求。
内容的提问来源于stack exchange,提问作者Andrés Camilo Arcila Ortiz
相关产品推荐
相关产品推荐

