What am I doing wrong with Sequelize? - node.js

I'm trying to use Sequelize for my simple Typescript application. I simply want to connect to Postgres db via Sequelize (I can) and create a simple table Book (I can't)
I've the file interface.ts within which I've the interface book:
export interface book{
title: string;
author: string;
price: number;
id: number;
}
Then I've the database.ts file:
import { Dialect, Sequelize } from 'sequelize'
import {book, purchases, user} from "../interface"
import { DataTypes, Model, Optional } from 'sequelize'
const dbName = process.env.DB_NAME as string
const dbUser = process.env.DB_USER as string
const dbHost = process.env.DB_HOST
const dbDriver = process.env.DB_DRIVER as Dialect
const dbPassword = process.env.DB_PASSWORD
export const sequelizeConnection = new Sequelize(dbName, dbUser, dbPassword, {
host: dbHost,
dialect: "postgres"
});
class Book extends Model<book> {
id!: number;
author!: string;
price!: number;
title!: string;
}
export function dbInit (){
Book.sync({force: true});
}
In the main file, index.ts:
async function Start() {
try {
await sequelizeConnection.sync();
dbInit();
app.listen(configuration.server_port, (): void => {
console.log("Server listening on port " + configuration.server_port);
});
} catch (error) {
console.log("Error occured: " + error);
}
}
Start();
The error I obtain is:
Executing (default): SELECT 1+1 AS result
Server listening on port 3000
(node:577) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hooks' of undefined
at getHooks (/mnt/c/Users/raffa/Desktop/esercitazione_ts/node_modules/sequelize/src/hooks.js:70:26)
at Function.runHooks (/mnt/c/Users/raffa/Desktop/esercitazione_ts/node_modules/sequelize/src/hooks.js:98:15)
at Function.sync (/mnt/c/Users/raffa/Desktop/esercitazione_ts/node_modules/sequelize/src/model.js:1339:18)
at dbInit (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/config/dabatase.ts:25:8)
at /mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:18:11
at step (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:56:23)
at Object.next (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:37:53) at fulfilled (/mnt/c/Users/raffa/Desktop/esercitazione_ts/src/index.ts:28:58)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:577) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:577) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
What am I doing wrong?

Related

Keycloak connection error using kcAdminClient and NestJS

I am working with keycloak and using this package https://www.npmjs.com/package/#keycloak/keycloak-admin-client to implement user edit functionality for every user. Backend is written on Nest.JS. This is app.service.ts code
import { Injectable } from '#nestjs/common';
import KcAdminClient from '#keycloak/keycloak-admin-client';
#Injectable()
export class AppService {
private adminClient: KcAdminClient;
constructor() {
this.getAdminProperties().then(admin => {
this.adminClient = admin;
})
}
async getAdminProperties() {
const kcAdminClient = new KcAdminClient();
await kcAdminClient.auth({
username: 'user',
password: 'user',
grantType: 'password',
clientId: 'admin-cli',
});
kcAdminClient.setConfig({
realmName: 'space-realm',
});
return kcAdminClient;
}
updateUser(body: any, id: number): any {
this.adminClient.users.update({ id: id.toString() }, body)
}
}
And after this all code I am getting this annoying error:
(node:732) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:8080
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
(node:732) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Maybe I am doing something wrong?
The problem was inside KcAdminClient() constructor, so for dev version I just added baseUrl with static IP of my Docker container of keycloak. For dev version this approach is fine, for public also, because you will use url of you web application. Good luck!

Mongoose query not running - "cursor.toArray is not a function"

MongoDB beginner, having trouble getting queries to work. Was following a tutorial of sorts and it was a demo notes app. Their syntax for saving new notes works fine.
However when it comes to printing out the list of notes, there seems to be something wrong in the syntax given to me or something im doing wrong.
const mongoose = require("mongoose");
const url =
"mongodb+srv://Saif:<password>#cluster0.8d2lb.mongodb.net/notes-app?retryWrites=true&w=majority";
mongoose.connect(url, {
useNewUrlParser: true,
});
const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean,
});
const Note = mongoose.model("Note", noteSchema);
Note.find({}).then((result) => {
result.forEach((note) => {
console.log(note);
});
mongoose.connection.close();
});
After looking up documentation, the actual syntax of find is a little different where they pass in a callback instead of using promises. But changing that block to use a callback still doesnt work
Note.find({}, (error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})
Error
TypeError: cursor.toArray is not a function
at model.Query.<anonymous> (D:\Folders\Documents\CS.........
(Use `node --trace-warnings ...` to show where the warning was created)
(node:27108) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:27108) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
.find method from model returns Query object not Cursor
For cursor you need to do .exec
Note.find({}).exec((error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})

CockroachDB with node js pg driver

I am trying to connect CockroachDB and Nodes JS using the pg driver. I am able to establish a connection successfully, but every time when querying the tables: it works only when I prefix the table names with the database name, or otherwise It throws relation doesn't exist error. Though I am specifying the database name while establishing DB connection.
The code that I am using to establish DB connection :
var pg = require('pg');
var config = {
user: 'root',
host: 'localhost',
database: 'testDB',
port: 26257
};
var pool = new pg.Pool(config);
const client = await pool.connect();
Executing this line works fine as I prefix table name with DBname:
const response = await client.query('select * from testDB.test');
Executing this line raises the following error:
const response = await client.query('select * from test');
(node:12797) UnhandledPromiseRejectionWarning: error: relation "test" does not exist
at Parser.parseErrorMessage (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/index.js:10:42)
at Socket.emit (events.js:314:20)
at addChunk (_stream_readable.js:304:12)
at readableAddChunk (_stream_readable.js:280:9)
at Socket.Readable.push (_stream_readable.js:219:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
at TCP.callbackTrampoline (internal/async_hooks.js:123:14)
(Use `node --trace-warnings ...` to show where the warning was created)
<node_internals>/internal/process/warning.js:33
(node:12797) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
<node_internals>/internal/process/warning.js:33
(node:12797) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Any kind of help is appreciated, Thanks in advance :)
EDIT: The database name should be all lowercase. See https://www.cockroachlabs.com/docs/stable/keywords-and-identifiers.html#rules-for-identifiers
defaultdb> CREATE DATABASE TeSt;
CREATE DATABASE
Time: 166.382ms
defaultdb> SHOW DATABASES;
database_name | owner
-----------------------------+---------------------
defaultdb | root
test | lauren
testdb | lauren
With CockroachDB v20.2.2 and pg v8.5.1, I'm not able to reproduce the issue. The below works as expected:
const { Pool } = require("pg");
const config = {
...
database: "testdb",
...
};
const pool = new Pool(config);
;(async function() {
const client = await pool.connect();
await client.query("select * from test_table", (err, res) => {
console.log(err, res);
client.end();
});
})()

Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead

I am learning typeorm with expressjs. Here I am trying to implement login user function where if user exist it will send an access token. I have already implemented Register function but while adding login I get error in console saying this. I have no idea what this means.
(node:8536) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(node:8536) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'isValidPassword' of undefined
at Object.<anonymous> (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:43:15)
at step (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:32:23)
at Object.throw (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:13:53)
at rejected (C:\Users\adity\Desktop\dev\restapi\src\controllers\AuthController.ts:5:65)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:8536) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8536) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here is my code.
AuthController.ts
static login = async (req: Request, res: Response) => {
const { email, password } = req.body;
if (!(email && password)) {
res.status(400).send();
}
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail({ where: email });
} catch (error) {
res.status(401).send(error);
}
if (!user.isValidPassword(password)) {
res.status(401).send("Incorrect Password");
return;
}
const token = jwt.sign({ id: user.id, email: user.email }, "secret", {
expiresIn: "1h",
});
res.send(token);
};
Entity/User.ts
import * as bcrypt from "bcryptjs";
#Entity()
export class User extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
email: string;
#Column()
#Length(4, 100)
password: string;
#Column()
#CreateDateColumn()
createdAt: Date;
#Column()
#UpdateDateColumn()
updatedAt: Date;
isValidPassword = (password: string) => {
return bcrypt.compareSync(password, this.password);
};
setPassword = (password: string) => {
return (this.password = bcrypt.hashSync(password, 8));
};
}
This NodeJS error usually happens when its detecting an asynchronous function somewhere in your code whose error is not being handled.
If getRepositry(user) is an async function, you could try attaching a catch block it like so:
const userRepository = await getRepository(User).catch(err=>console.log(err));
This should take care of unhandled promise rejection error.
This is happening because in case findOneOrFail could not find any user it will through error that you are catching but it will result in user value equal to undefined.
Then the method isValidPassword will not work as it is not defined on the undefined but on the user model
if (!user.isValidPassword(password)) {
res.status(401).send("Incorrect Password");
return;
}
you should move above code in the try block or you can place a type guard in front like this
if (user && !user.isValidPassword(password)) {
res.status(401).send("Incorrect Password");
return;
}

UnhandledPromiseRejectionWarning: Unhandled promise rejection. MongoNetworkError: failed to connect to server [localhost:27017]

I'm attempting to create a node.js app that encompasses both grapgql with MongoDB for databasing, though I'm fairly new to graphql.
I'm using GraphQLPlayground in the browser. The error encountered seems to be about promises, I'm not much familiar with the concept.
const { GraphQLServer} = require('graphql-yoga');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/librarydb')
const Book = mongoose.model("Book", {
author: String,
title: String,
available: Boolean
});
//initialization of grapgql schema
const typeDefs = `
type Query {
bookDetails(title: String): String!
}
type Book{
id: ID!
title: String!
available: Boolean!
}
type Mutation{
createBook(title: String!): Book
}`;
//reflects the structure of the schema
const resolvers = {
Query: {
bookDetails: (_, {title}) => `Book ${title || "not available"}`,
},
Mutation: {
createBook: async (_, { title }) => {
const book = new Book({ title, available: false});
await book.save();
return book;
}
}
};
const server = new GraphQLServer({typeDefs, resolvers});
mongoose.connection.once("open", function() {
server.start(() => console.log('Connection to server created successfully'));
});
Initially a connection was made but when I started including a
mongodb to my code I encountered the error below:
(node:480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1):
MongoNetworkError: failed to connect to server [localhost:27017] on first
connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:480) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.
js process with a non-zero exit code.
I have explored similar questions but they all seem to be variations of the error and none seem to address this specific issue, thanks in advance.

Resources