I am importing crypto-js in a Nestjs service, and I run into this error
TypeError: Cannot read properties of undefined (reading 'enc')
at CryptoUtilsService.decryptAESHex
The code:
import { Injectable, Logger } from '#nestjs/common';
import { CmacDto, Crc32Dto } from './dto';
import CryptoJS from 'crypto-js';
import { AesDecryptDto } from './dto/aesDecrypt.dto';
#Injectable()
export class CryptoUtilsService {
private readonly logger = new Logger(CryptoUtilsService.name);
decryptAESHex(data: AesDecryptDto) {
let keyHex = CryptoJS.enc.Hex.parse(data.key);
let ivHex = CryptoJS.enc.Hex.parse(data.iv);
let encryptedWordArray = CryptoJS.enc.Hex.parse(
data.encryptedData.toUpperCase(),
);
let encString = CryptoJS.enc.Base64.stringify(encryptedWordArray);
// console.log("before decryption: ", encryptedString.toUpperCase(), encString);
let decryptedResp = CryptoJS.AES.decrypt(encString, keyHex, {
iv: ivHex,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.NoPadding,
});
// console.log("after decryption:: ", decryptedResp)
return CryptoJS.enc.Hex.stringify(decryptedResp).toUpperCase();
}
}
I have installed crypto-js and #types/crypto-js module. Also tried deleting the node_modules and installing again.
It seems to work fine on other node projects without typescript. I cannot figure out what is going wrong here.
crypto-js doesn't use default exports for its base package, use import * as CryptoJS from 'crypto-js' to import the package correctly
Related
We have a gRPC repo that has a JS implementation of creating a client.
/**
* Code generated by protoc-gen-twirp_js v5.0.0, DO NOT EDIT.
* source: domain_service/service.proto
*/
// import our twirp js library dependency
var createClient = require("twirp");
// import our protobuf definitions
var pb = require("./domain_service/service_pb.js");
Object.assign(module.exports, pb);
/**
* Creates a new DomainClient
*/
module.exports.createDomainClient = function(baseurl, extraHeaders, useJSON) {
var rpc = createClient(baseurl, "events.domain_service.Domain", "v5.0.0", useJSON, extraHeaders === undefined ? {} : extraHeaders);
return {
fireDomainEvent: function(data) { return rpc("FireDomainEvent", data, pb.FireDomainEventResponse); }
}
}
I created a d.ts file in the same folder using TS playground
export function createDomainClient(
baseurl: any,
extraHeaders: any,
useJSON: any
): {
fireDomainEvent: (data: any) => any;
};
But when I try to implement the code:
import { createDomainClient } from '#MyOrganization/package';
const client = new createDomainClient(
'https://my.url.com', '', false
);
I get the follow error: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)
I am simply trying to import the commonJS client into my Typescript project with making the least amount of changes on the gRPC repo side.
Either explicitly set any type for client
import { createDomainClient } from '#MyOrganization/package';
const client: any = new createDomainClient(
'https://my.url.com', '', false
);
Or add a construct signature to the type
How does interfaces with construct signatures work?
I am trying to develop for a package that only runs on some systems. There is a "mock" version of the package that exists as well.
I'd like a "module" that I can import from my main that automatically falls back to the "mock" version of the package when the main package fails to import (either because it did not install because of os/engine restrictions or it failed on startup).
This is what I have so far:
import { Gpio as GpioClass, GpioBank as GpioBankClass, Notifier as NotifierClass } from 'pigpio';
let pigpio: {
Gpio: typeof GpioClass;
GpioBank: typeof GpioBankClass;
Notifier: typeof NotifierClass;
};
try {
pigpio = require('pigpio');
} catch (e) {
process.env.PIGPIO_NO_LOGGING = 'yes';
pigpio = require('pigpio-mock');
}
export const { Gpio, GpioBank, Notifier } = pigpio;
This kind of works but seems to cause some import errors/ordering issues with other parts of my code.
I suspect that using import and export will be better in the long run. Maybe this is a flawed assumption. I'm still not 100% clear on how exactly import/export works.
I've tried using the "async" import(...) function to no avail:
import { Gpio as GpioClass, GpioBank as GpioBankClass, Notifier as NotifierClass } from 'pigpio';
let pigpio: Promise<{
Gpio: typeof GpioClass;
GpioBank: typeof GpioBankClass;
Notifier: typeof NotifierClass;
}>;
try {
pigpio = import('pigpio');
} catch (e) {
process.env.PIGPIO_NO_LOGGING = 'yes';
pigpio = import('pigpio-mock');
}
// This doesn't work. Cannot use top level await.
export const { Gpio, GpioBank, Notifier } = await pigpio;
Is there some part of how export works that I'm missing? Or maybe it's like how you can await a non-async function as long as it returns a Promise and I just need to module.exports = import(...)? That doesn't seem to work however.
The cherry on top would be to get the type information correct for TypeScript.
I'm trying to access a exported Cache into another file, but not having success.
Basically I've got two files:
cache.ts I'll expose only the part that meter
import Cache = require('node-cache');
const narrativeCache: Cache = New Cache();
protected setNarrativeCache(): void {
narrativeCache.set(123,'abc',0);
}
module.exports.narrativeCache = narrativeCache;
I want use this narrative in this other file:
module.ts
import { narrativeCache } from '../transport/cache.ts';
function test1(): void {
narrativeCache.get(123); //Error in here, it doesn't find this
}
Files tree:
src\transport\cache.ts
src\reader\module.ts
The error is because it doesn't find this narrativeCache.
The error was becausing of typescript export type:
Here's the solution
export const narrativeCache: Cache = new Cache();
I'm trying to use the ES6 import syntax and keep running into errors.
This is my data type,
class UnionFind{
constructor(n){
this.items = n;
}
union(p, q){
}
connected(p, q){
}
find(p){
}
count(){
}
}
export default UnionFind
Saved in a file UnionFind.js
This the calling client,
import { UnionFind } from './unionFind';
const readline = require('readline');
const rl = readline.createInterface({
input:process.stdin,
output:process.stdout,
terminal:false
});
uf = new UnionFind(10)
rl.on('numbers', function (line) {
arr = number.split(' ')
console.log(arr);
});
This is saved in a file client.mjs
This is how I'm running it,
node --experimental-modules union-find/client.mjs
I get the following error,
(node:13465) ExperimentalWarning: The ESM module loader is experimental.
file:///Users/mstewart/Dropbox/data-structures-algorithms-princeton/union-find/client.mjs:1
import { UnionFind } from './unionFind';
^^^^^^^^^
SyntaxError: The requested module does not provide an export named 'UnionFind'
at ModuleJob._instantiate (internal/modules/esm/ModuleJob.js:89:21)
at <anonymous>
What am I doing wrong here?
In this case, use
import UnionFind from './UnionFind.js';
if you declared
export class UnionFind{ ....
then you use
import { UnionFind } from './UnionFind.js';
Also take a look at the file name: UnionFind.js . You are using './unionFind'. This is case sensitive
What must the module code (writen in typescript) look like to be able to use it like this:
/// <reference path="./onoff.ts" />
//import * as onoff from "./onoff";
var onoff = require("./onoff");
var app = onoff();
var computers: Onoff.Computer[] = [];
app.start(computers);
I was sure it must be this, but it does not work:
import * as express from "express";
export module Onoff {
export class Computer {
}
export class OnoffApp {
start(computers:Computer[], port:number = 3489) {
...
}
}
export default function() {
return new OnoffApp();
}
}
Typescript complains:
service/example.ts(5,11): error TS2349: Cannot invoke an expression whose type lacks a call signature.
service/example.ts(7,16): error TS2503: Cannot find namespace 'Onoff'.
service/example.ts(8,21): error TS2503: Cannot find namespace 'Onoff'.
typings/express/express.d.ts(14,1): error TS6053: File 'typings/serve-static/serve-static.d.ts' not found.
typings/express/express.d.ts(28,34): error TS2307: Cannot find module 'serve-static'.
thank you very much! I have no Idea what I've done wrong...
Judging from the error description, moving the import outside of your module should fix your problem:
import * as express from "express";
export module Onoff {
...
}
You import your module as onoff but are trying to use Onoff
var onoff = require("./onoff");
^
var computers: Onoff.Computer[] = [];
^