How to fix "can not fin'd bcrypt" in NestJS? - nestjs

As found in this SO-answer, the following thing could be a way how to encrypt a password into a hash:
#BeforeInsert() async hashPassword() {
this.password = await bcrypt.hash(this.password, Number(process.env.HASH_SALT));
}
However, although I have installed "bcrypt" and "types/bcrypt", it can't get found by NodeJS:
src/entities/user.entity.ts:50:27 - error TS2552: Cannot find name
'bcrypt'. Did you mean 'crypto'?
In my package.json the following lines show that bcrypt was successfully installed:
"#types/bcrypt": "^5.0.0",
"bcrypt": "^5.0.1",
How to fix this?

Import the bcrypt on the files where you use it like this:
import * as bcrypt from 'bcrypt';

Related

Cannot find module 'node:url' when executing typescript from webstorm

I have written this small typescript hello world example
import axios from 'axios';
import { wrapper } from 'axios-cookiejar-support';
import { CookieJar } from 'tough-cookie';
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
client.get('https://example.com');
when I run this from webstorm i get the following error
/usr/bin/node /usr/local/lib/node_modules/ts-node/dist/bin.js /home/nayana/WebstormProjects/hello-world/hello.ts
Error: Cannot find module 'node:url'
anyone have idea on how to resolve this?
I already tried npm install node:url and url
i have isolated the error to this line
const client = wrapper(axios.create({ jar }));
The issue maybe is related to the node version.
The axios-cookiejar-support requires a specific node version ("node": ">=14.18.0 <15.0.0 || >=16.0.0").
Check node --version and package-lock.json.
Sample:
"node_modules/axios-cookiejar-support": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/axios-cookiejar-support/-/axios-cookiejar-support-4.0.3.tgz",
"integrity": "sha512-fMQc0mPR1CikWZEwVC6Av+sD4cJuV2eo06HFA+DfhY54uRcO43ILGxaq7YAMTiM0V0SdJCV4NhE1bOsQYlfSkg==",
"dependencies": {
"http-cookie-agent": "^4.0.2"
},
"engines": {
"node": ">=14.18.0 <15.0.0 || >=16.0.0"
},
"peerDependencies": {
"axios": ">=0.20.0",
"tough-cookie": ">=4.0.0"
}
},
You might need to install a later version of node.js.
I was running 14.17.6 and after installing 16.17.0 with nvm then I was able to run the project.
If you have nvm installed you can install a specific version of node e.g.
nvm install 16.17.0
make sure the types array in your tsconfig.json file contains "node"
{
"compilerOptions": {
"types": [
// ... your other types
"node"
],
// ... your other settings
},
}
The only thing you need to do, if you didn't install typescript is to change in the vite.config.js file, the import line like this:
import { fileURLToPath, URL } from 'node:url'
To:
import { fileURLToPath, URL } from 'url'

run cypress using tags

I am using Cypress (version:10+) + Cucumber+ Typescript. I need to run the test using tags. Also, I tried cypress-tag but it's not working. Is there a way I can run the cypress test using tags without skipping the test?
You can refer to this sample repository for your setup check it here:
https://github.com/badeball/cypress-cucumber-preprocessor/tree/master/examples/browserify-ts
in your cypress.config.ts
import { defineConfig } from "cypress";
import { addCucumberPreprocessorPlugin } from "#badeball/cypress-cucumber-preprocessor";
import browserify from "#badeball/cypress-cucumber-preprocessor/browserify";
async function setupNodeEvents(
on: Cypress.PluginEvents,
config: Cypress.PluginConfigOptions
): Promise<Cypress.PluginConfigOptions> {
await addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
browserify(config, {
typescript: require.resolve("typescript"),
})
);
// Make sure to return the config object as it might have been modified by the plugin.
return config;
}
export default defineConfig({
e2e: {
specPattern: "**/*.feature",
supportFile: false,
setupNodeEvents,
},
});
in your package.json should contain the following dependencies and important to set cypress-cucumber-preprocessor settings "filterSpecs: true" and "omitFiltered: true" to run successfully through tags
{
"dependencies": {
"#badeball/cypress-cucumber-preprocessor": "latest",
"#cypress/browserify-preprocessor": "latest",
"cypress": "latest",
"typescript": "latest"
},
"cypress-cucumber-preprocessor": {
"filterSpecs": true,
"omitFiltered": true
}
}
then you can run your feature files like this:
cypress run --env tags=#foo
Best solution to it is the Cucumber Cypress preprocessor. I was able run my test using tags without any issue. The problem I faced in Cypress version 10 was the Itegration folder in the Cypress folder structure was renamed to e2e folder. And in Cucumber-Cypress-preprocessor will always look for files in integration folder (which was there in Cypress version less than 10) for searching tags.
I think the better solution is cypress-grep you can check about cypress-grep in the follow link https://github.com/cypress-io/cypress-grep

typeORM No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command

I'm doing a course where we are using express-node postgres and react (with typescript) and typeORM. Everything has worked well so far, but I'm facing an issue with typeORM and I don't know what is going and why is this error happening
The Big Problem : So, the problem is that, I was doing the auth, and at some point we changed users schema in the DB so we had to make a migration, but, before migration, we did npm run typeorm schema:drop ,but when I tried, this happened with migration
This is the first command I used
npm run typeorm migration:generate -- --n create-users-table
This was the error
> new-typeorm-project#0.0.1 typeorm C:\Users\diego cifuentes\Desktop\Studying Backend\redit> ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"
bin.js migration:generate
Generates a new migration file with sql needs to be executed to update
schema.
Opciones:
-h, --help Muestra ayuda [booleano] -c, --connection Name of the connection on which run a query.
[defecto: "default"] -n, --name Name of the migration class.
[cadena de caracteres] [requerido] -d, --dir Directory where migration should be created.
-p, --pretty Pretty-print generated SQL
[booleano] [defecto: false] -f, --config Name of the file with connection configuration.
[defecto: "ormconfig"] -o, --outputJs Generate a migration file on Javascript instead of
Typescript [booleano] [defecto: false] --dr, --dryrun Prints out the contents of the migration instead of
writing it to a file [booleano] [defecto: false] --ch, --check Verifies that the current database is up to date and that no migrations are needed. Otherwise exits with
code 1. [booleano] [defecto: false] -v, --version Muestra número de versión [booleano]
Falta argumento requerido: n
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! new-typeorm-project#0.0.1 typeorm: `ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the new-typeorm-project#0.0.1 typeorm script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\diego cifuentes\AppData\Roaming\npm-cache\_logs\2021-05-11T15_29_02_081Z-debug.log
After hours trying to search for solution everywhere, I change the last command to this one
npx typeorm migration:generate -- --n create-users-table
And the error was different this time, looks like this
No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command
So, I said, ok, I'm getting closer to fixing this, but... After hours ( again ) looking for a new answer, I couldn't find anything, so, I'm getting to a point where I need to write this post in order to fix my problem. So now, let me show you my ormconfig, my package.json and the entity I want to migrate in my postgres DB.
package.json (the script typeorm is at the end)
{
"name": "new-typeorm-project",
"version": "0.0.1",
"description": "Awesome project developed with TypeORM.",
"devDependencies": {
"#types/bcrypt": "^5.0.0",
"#types/cookie": "^0.4.0",
"#types/cookie-parser": "^1.4.2",
"#types/express": "^4.17.11",
"#types/jsonwebtoken": "^8.5.1",
"#types/morgan": "^1.9.2",
"#types/node": "^15.0.2",
"morgan": "^1.10.0",
"nodemon": "^2.0.7",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
},
"dependencies": {
"bcrypt": "^5.0.1",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"cookie": "^0.4.1",
"cookie-parser": "^1.4.5",
"dotenv": "^9.0.1",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"pg": "^8.4.0",
"reflect-metadata": "^0.1.10",
"typeorm": "0.2.32"
},
"scripts": {
"start": "ts-node src/server.ts",
"dev": "nodemon --exec ts-node src/server.ts",
"typeorm": "ts-node ./node_modules/typeorm/cli.js"
}
}
ormconfing.json Quick note : I changed entities, migrations and subscribers to .js, because with .ts was always giving me error.
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "**",
"password": "**",
"database": "**",
"synchronize": true,
"logging": true,
"entities": ["src/entities/**/*.js"],
"migrations": ["src/migrations/**/*.js"],
"subscribers": ["src/subscribers/**/*.js"],
"cli": {
"entitiesDir": "src/entities",
"migrationsDir": "src/migrations",
"subscribersDir": "src/subscribers"
}
}
And last thing I want to show you, even though it might not be that important, this is the users schema
import {
Entity as TOEntity,
Column,
Index,
BeforeInsert,
OneToMany
} from "typeorm";
import bcrypt from "bcrypt";
import { IsEmail, Length } from "class-validator";
import { Exclude } from "class-transformer";
import Entity from "./Entity";
// import Post from "./Post";
#TOEntity("users")
export default class User extends Entity {
constructor(user: Partial<User>) {
super();
Object.assign(this, user);
}
#Index()
#IsEmail()
#Column({ unique: true })
email: string;
#Index()
#Length(3, 200)
#Column({ unique: true })
username: string;
#Exclude()
#Length(6, 200)
#Column()
password: string;
// #OneToMany(() => Post, post => post.user)
// posts: Post[];
#BeforeInsert()
async hashedPassword() {
this.password = await bcrypt.hash(this.password, 6);
}
}
End Goal: So, if you can help me with this, you will save my life. One last thing is that I tried to post my problems first in the Spanish website of stack overflow, but nobody could help me, so maybe here someone will, thanks for your time and take care!
Change your entities, migrations and subscribers into your dist directory.
e.g.:
entities: ["dist/entities/**/*{.js,.ts}"],
migrations: ["dist/migrations/**/*{.js,.ts}"],
subscribers: ["dist/subscribers/**/*{.js,.ts}"],
dist directory is the directory which gets created when you build the app. You can find your dist directory using tsconfig.json -> compilerOptions -> outDir.
Then build your app again using npm run build and try to generate the migrations.
For me the ormconfig.json's was like this,
"entities": [
"dist/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
Changing it to
"entities": [
"src/entity/**/*{.js,.ts}"
],
"migrations": [
"src/migration/**/*{.js,.ts}"
],
"subscribers": [
"src/subscriber/**/*{.js,.ts}"
],
generated the migration correctly.
And the package.json script is like this
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
And the command used is
npm run typeorm migration:generate -- -n FileAddTemporaryDeletedFields -p --dr --ch
I've seen this error, and if I'm not mistaken it's because I was trying to create a bank that had already been created.
This command below deletes all tables:
yarn typeorm query "DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT USAGE ON SCHEMA public to PUBLIC; GRANT CREATE ON SCHEMA public to PUBLIC; COMMENT ON SCHEMA public IS 'standard public schema';"
then:
yarn typeorm --migration:generate -n migration_name -d path/to/your/migrations/
ormconfig.json is deprecated in latest version as i know.
but anyway I'm gonna share my solution when i used old version.
when generate, typeorm first reads ormconfig.json and login into rdbms.
and compares between 'the actual schema of db' and
'schema file as ormconfig.json[entities]'
so, if the file (writen at 'entities' in ormconfig.json) is in dist folder.
you have to edit that .js file.(not .ts file in src folder)
but, if the 'entities' file is in src folder as ormconfig.json,
check if 'autosave' feature of vscode is on.
if you 'npm run start:dev'
It could be the case that the actual schema of db has been already modified
before you edit entities file.

jest-haste-map:Duplicate module name: react-animated

After adding react-native-push-notification and #react-native-community/push-notification-ios I am facing the error:
Error: jest-haste-map: Haste module naming collision:
Duplicate module name: react-animated
Paths: /<projectPath>/node_modules/#react-native-community/push-notification-ios/node_modules/react-native/Libraries/Animated/release/package.json collides with /<projectPath>/node_modules/react-native/Libraries/Animated/release/package.json
This error is caused by `hasteImpl` returning the same name for different files.
at setModule (/<projectPath>/node_modules/jest-haste-map/build/index.js:569:17)
at workerReply (/<projectPath>/node_modules/jest-haste-map/build/index.js:641:9)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Promise.all (index 77)
I did add blacklist to rn-cli.config.js
cleared yarn cache, removed node_modules, cleared watchman and re-run
None helped.
"react": "16.8.3",
"react-native": "0.59.10",
"#react-native-community/push-notification-ios": "^1.2.0",
"react-native-push-notification": "^3.5.2",
I did add the blacklist to metro.config.js NOT rn-cli.config.js
// metro.config.js
var blacklist = require('metro-config/src/defaults/blacklist');
module.exports = {
resolver: {
blacklistRE: blacklist([
/node_modules\/.*\/node_modules\/react-native\/.*/,
])
},
};

bundle.js bundle.js:1 Uncaught Error: Cannot find module '/node_modules\mongodb-core\lib\topologies/../../package.json'

I am getting the below error:
bundle.js:1 Uncaught Error: Cannot find module '/node_modules\mongodb-ore\lib\topologies/../../package.json'
Here is my version detial:
OS: Windows10
MongoDB: 2.2.16
MongoDB-core: 2.1.2
Node: 6.9.2
I have used npm install bson-ext and changed \node_modules\mongodb-core\node_modules\bson-ext\ext\index.js to
try {
// Load the precompiled win32 binary
if(process.platform == "win32" && process.arch == "x64") {
bson = require('bson');
} else if(process.platform == "win32" && process.arch == "ia32") {
bson = require('bson');
} else {
bson = require('bson');
}
} catch(err) {
console.log(err)
// Attempt to load the release bson version
try {
bson = require('bindings')('bson.node');
} catch (err) {
throw new Error("js-bson: Failed to load c++ bson extension, using pure JS version");
}
}
while the original is:
bson = require('./win32/x64/bson');
because when I try browserify range.js > bundle.js, it cannot find bson-ext module in mongoDB-core.
I am not sure whether this kind of operation may cause the above error.
Here is my package.json file :
"dependencies": {
"browserify": "^13.1.1",
"bson": "^1.0.1",
"d3": "^4.4.0",
"express": "^4.14.0",
"hbs": "^4.0.1",
"jsdom": "^9.9.1",
"mongodb": "^2.2.16",
"mongodb-core": "^2.1.2"
}
I haven't been able to confirm this yet, but I think the problem is that MongoDB's JavaScript (Node.js) driver is not intended for use in a browser, for security reasons. Not clear if the problem in the OP is due to Browserify incorrectly resolving relative paths or something else, but regardless the preferred technique is to proxy requests to your MongoDB instance via a Node server.
Mongo lists off-the-shelf solutions for this here:
https://docs.mongodb.com/ecosystem/tools/http-interfaces/
Note also the --rest option, which allows an application to read directly from the DB via a URL schema:
https://docs.mongodb.com/ecosystem/tools/http-interfaces/#simple-rest-api
As the docs mention, this is not good practice for security concerns, but may help with prototyping.

Resources