How to use npm library in NestJs

196 Views Asked by At

I'm new into NestJs and I've been trying to use the mathjs library inside a custom decorator in order to verify that a string is a valid unit of measurement (would also appreciate guidance on this) but I've been getting the following error, and I'm guessing I don't understand how to correctly use a 3rd party library

TypeError: Cannot read properties of undefined (reading 'unit')
    at Object.validate (D:\Documentos\Camilo\Mercadonde\pricesmart_api_proxy\src\validation\is-measurement-unit.ts:14:28)    at CustomConstraint.validate (D:\Documentos\Camilo\Mercadonde\pricesmart_api_proxy\node_modules\src\register-decorator.ts:63:26)
    at D:\Documentos\Camilo\Mercadonde\pricesmart_api_proxy\node_modules\src\validation\ValidationExecutor.ts:271:68     
    at Array.forEach (<anonymous>)
    at D:\Documentos\Camilo\Mercadonde\pricesmart_api_proxy\node_modules\src\validation\ValidationExecutor.ts:253:82     
    at Array.forEach (<anonymous>)
    at ValidationExecutor.customValidations (D:\Documentos\Camilo\Mercadonde\pricesmart_api_proxy\node_modules\src\validation\ValidationExecutor.ts:252:15)
    at ValidationExecutor.performValidations (D:\Documentos\Camilo\Mercadonde\pricesmart_api_proxy\node_modules\src\validation\ValidationExecutor.ts:212:10)
    at D:\Documentos\Camilo\Mercadonde\pricesmart_api_proxy\node_modules\src\validation\ValidationExecutor.ts:114:14     
    at Array.forEach (<anonymous>)

Here is my code so far

import { ValidationArguments, registerDecorator } from 'class-validator';
import 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 unit of measurement' },
      validator: {
        async validate(value: any, args: ValidationArguments) {
          console.log(math.unit(45, 'cm'));
          console.log(value);
          return true;
        },
      },
    });
  };
}

I've also checked the custom provider solution, but it seems like over engineering, is there an easiest way?

1

There are 1 best solutions below

2
Micael Levi On BEST ANSWER

the runtime is nodejs. So you can use any nodejs package in nestjs apps.

The issue you're facing is with typescript, not nestjs.

You can do: import * as math from 'mathjs'; or enable the allowSyntheticDefaultImports compiler option.