Unhandled promise rejection using NestJS - javascript

When I execute the following code I get "201 Created" response from the server but actually data is not inserted in the server.
I am using nestJS with TypeORM and Postgres for my application.
import { Repository, EntityRepository } from "typeorm";
import { User } from './user.entity';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { ConflictException, InternalServerErrorException } from "#nestjs/common";
#EntityRepository(User)
export class UserRepository extends Repository<User>{
async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void>{
const {username, password} = authCredentialsDto;
const user = new User();
user.username = username;
user.password = password;
try{
await user.save();
} catch (error) {
if (error.code === '23505'){ // error code for duplicate value in a col of the server
throw new ConflictException('Username already exists');
} else {
throw new InternalServerErrorException();
}
}
}
}
And I get following response in the VS Code terminal, instead of getting "201 Crated" from the server:
(node:14691) UnhandledPromiseRejectionWarning: Error: Username already exists
at UserRepository.signUp (/home/rajib/practicing coding/nestJS-projects/nestjs-task-management/dist/auth/user.repository.js:24:23)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:14691) 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:14691) [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.
And the controller modules code is following:
import { Controller, Post, Body, ValidationPipe } from '#nestjs/common';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
#Controller('auth')
export class AuthController {
constructor( private authService: AuthService){}
#Post('/signup')
signUp(#Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto): Promise<void>{
return this.authService.signUp(authCredentialsDto);
}
}

Good day.
I think the issue you have here is not awaiting the method call to the authService.signup() method in your AuthController...
So, the correction should be:
In the AuthService::signup() method:
return this.userRepository.signup(authCredentialsDto);
In the AuthController::signup() method:
return this.authService.signup(authCredentialsDto);

Related

Not getting a 404 for Patch for user that does not exist

I am expecting that when I send a PATCH/update to a user that does not exist, I should get back a 404, but instead I am getting back a 200.
### Update a user
PATCH http://localhost:3000/auth/2345678
Content-Type: application/json
{
"password": "letmein"
}
HTTP/1.1 200 OK
X-Powered-By: Express
Date: Thu, 09 Sep 2021 19:41:13 GMT
Connection: close
Content-Length: 0
In the console I do get back:
(node:36780) UnhandledPromiseRejectionWarning: NotFoundException: user
not found
at UsersService.update (/Users/luiscortes/Projects/car-value/src/users/users.service.ts:27:13)
(Use node --trace-warnings ... to show where the warning was
created) (node:36780) 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:36780) [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. (node:36780) UnhandledPromiseRejectionWarning:
NotFoundException: user not found
at UsersService.update (/Users/luiscortes/Projects/car-value/src/users/users.service.ts:27:13)
(node:36780) 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)
but why don't I get a 404 in my REST Client?
This is my users.controller.ts file:
import {
Body,
Controller,
Post,
Get,
Patch,
Param,
Query,
Delete,
NotFoundException,
} from '#nestjs/common';
import { CreateUserDto } from './dtos/create-user.dto';
import { UpdateUserDto } from './dtos/update-user.dto';
import { UsersService } from './users.service';
#Controller('auth')
export class UsersController {
constructor(private usersService: UsersService) {}
#Post('/signup')
createUser(#Body() body: CreateUserDto) {
this.usersService.create(body.email, body.password);
}
#Get('/:id')
async findUser(#Param('id') id: string) {
const user = await this.usersService.findOne(parseInt(id));
if (!user) {
throw new NotFoundException('user not foud');
}
return user;
}
#Get()
findAllUsers(#Query('email') email: string) {
return this.usersService.find(email);
}
#Delete('/:id')
removeUser(#Param('id') id: string) {
return this.usersService.remove(parseInt(id));
}
#Patch('/:id')
updateUser(#Param('id') id: string, #Body() body: UpdateUserDto) {
this.usersService.update(parseInt(id), body);
}
}
This is my users.service.ts file:
import { Injectable, NotFoundException } from '#nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '#nestjs/typeorm';
import { User } from './user.entity';
#Injectable()
export class UsersService {
constructor(#InjectRepository(User) private repo: Repository<User>) {}
create(email: string, password: string) {
const user = this.repo.create({ email, password });
return this.repo.save(user);
}
findOne(id: number) {
return this.repo.findOne(id);
}
find(email: string) {
return this.repo.find({ email });
}
async update(id: number, attrs: Partial<User>) {
const user = await this.findOne(id);
if (!user) {
throw new NotFoundException('user not found');
}
Object.assign(user, attrs);
return this.repo.save(user);
}
async remove(id: number) {
const user = await this.findOne(id);
if (!user) {
throw new NotFoundException('user not found');
}
return this.repo.remove(user);
}
}
You don't return the service call in your path request, so Nest doesn't know to wait for it. The service code then runs in the background after the response has been sent, and causes this unhandledPromiseRejection to show up. Change your patch method to this
#Patch('/:id')
updateUser(#Param('id') id: string, #Body() body: UpdateUserDto) {
return this.usersService.update(parseInt(id), body);
}

I am getting a 400 bad request while using google custom search with discord.js! what am I doing wrong here?

I am building a discord bot which searches a query on google using the custom search api but i am getting this error! here's my code, what am i doing wrong?
const Discord = require("discord.js");
const request = require("node-superfetch");
var fs = require('fs');
module.exports = {
name: 'google',
description: "searches google ",
cooldown: 10,
permissions: [],
async execute(message, args, cmd, client, Discord) {
let googleKey = "XXXX";
let csx = "be4b47b9b3b849a71";
let query = args.join(" ");
let result;
if(!query) return message.reply("Please enter a Valid Query");
result = await search(query);
if (!result) return message.reply("Invalid Search");
const embed = new Discord.MessageEmbed()
.setTite(result.title)
.setDescription(result.snippet)
.setImage(result.pagemap ? result.pagemap.cse_thumbnail[0].src : null)
.setURL(result.link)
.setColor(0x7289DA)
.setFooter("Powered by Google")
return message.channel.send(embed);
async function search(query) {
const { body } = await request.get("https://customsearch.googleapis.com/customsearch/v1").query({
key: googleKey, cs: csx, safe: "off", q: query
});
if(!body.items) return null;
return body.items[0];
}
}
}
ERROR MESSAGE: (node:10944) UnhandledPromiseRejectionWarning: Error: 400 Bad Request
at Request._request (D:\Coding\FLASH\node_modules\node-superfetch\index.js:58:16)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async search (D:\Coding\FLASH\commands\google.js:31:26)
at async Object.execute (D:\Coding\FLASH\commands\google.js:17:14)
(Use node --trace-warnings ... to show where the warning was created)
(node:10944) 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:10944) [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.

Setting "params" for GET requests using RESTDataSource

Problem: I am trying to make a GET request using RESTDataSource's get method, but I'm receiving a ERR_INVALID_URL error.
My code:
async getMediaIDs() {
let response;
try {
response = await this.get(`${process.env.INSTA_ID}/media`, {
access_token: `${process.env.PAGE_ACCESS_TOKEN}`,
});
} catch(err) {
throw new Error(err);
}
return response.data.data;
}
Expected: The request is successful, with the full url being:
https://graph.facebook.com/{insta_id}/media?access_token={access_token}
Actual: I receive this error:
2019-11-15T10:03:42.974335+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: Error: TypeError [ERR_INVALID_URL]: Invalid URL: 17841402041188678/media
2019-11-15T10:03:42.974379+00:00 app[web.1]: at InstagramAPI.getMediaIDs (/app/src/data/instagram.js:17:13)
2019-11-15T10:03:42.974382+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:93:5)
2019-11-15T10:03:42.974395+00:00 app[web.1]: (node:4) 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(). (rejection id: 3)
2019-11-15T10:03:42.974467+00:00 app[web.1]: (node:4) [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 suspect that the error is in
this.get(`${process.env.INSTA_ID}/media`, {
access_token: `${process.env.PAGE_ACCESS_TOKEN}`,
});
because I am not setting the params parameter correctly (...I think. I don't know.)
While searching for a solution, I found the RESTDataSource file, which leads to this:
protected async get<TResult = any>(
path: string,
params?: URLSearchParamsInit, // <----- (What I'm trying to set)
init?: RequestInit,
): Promise<TResult> {
return this.fetch<TResult>(
Object.assign({ method: 'GET', path, params }, init),
);
}
Following URLSearchParamsInit leads to this:
export type URLSearchParamsInit =
| URLSearchParams
| string
| { [key: string]: Object | Object[] | undefined }
| Iterable<[string, Object]>
| Array<[string, Object]>;
I'm not too familiar with TypeScript, but I'm guessing that those are ways to define params?.
Anyways, my question is how do I set the params parameter for RESTDataSource's get method?
side note for the Apollo devs: An API page for RESTDataSource would be brilliant! I would be willing to help document it, as proper documentation currently isn't available.
Based on the error you're seeing, it doesn't look like you're setting a baseURL. Without the baseURL set, you end up with 17841402041188678/media as the complete URL, which is not a valid URL. You can set the baseURL inside your RESTDataSource's constructor:
class InstagramAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://graph.facebook.com/';
}
// ...
}

Node JS self._callback.apply is not a function error

import axios from 'axios';
import * as jwt from 'jsonwebtoken';
import { Action } from 'routing-controllers';
import { Connection } from 'typeorm';
import { env } from '../env';
export function authorizationChecker(connection: Connection):
(action: Action, roles: any[]) => Promise<boolean> | boolean {
let validationKey: any = axios.get(env.auth.jwksUri).then(response => {
validationKey = response.data.keys[0].value;
}).catch();
return async function innerAuthorizationChecker(
action: Action,
roles: string[]
): Promise<boolean> {
// here you can use request/response objects from action
// also if decorator defines roles it needs to access the action
// you can use them to provide granular access check
// checker must return either boolean (true or false)
// either promise that resolves a boolean value
try {
const token = (action.request.headers.token ||
action.request.headers.authorization).replace('Bearer ', '');
await jwt.verify(token, validationKey);
return true;
} catch (e) {
return false;
}
};
}
This is my error:
error: [app] Application is crashed: TypeError: self._callback.apply is not a
function
(node:512) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): TypeError: Cannot read property '0' of undefined
(node:512) [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'm trying to get the validation key set from a specific URL from a service, but somehow (without calling the function) it says that the response data is undefined. On top of that, I'm having this error: self._callback.apply is not a function.
Has someone dealt with such a callback error before? I couldn't find anything on stackoverflow relating to my problem.

Calling a promise in a test get error 400 in NodeJS

I'm trying to use Contentful, a new JS library for building static websites. I want to use it in Node JS.
I created an app file like this (the name is getContent.js):
'use strict';
var contentful = require('contentful')
var client = contentful.createClient({
space: '****',
accessToken: '****'
});
module.exports = client;
function getEntry() {
return client.getEntry('******')
.then(function (entry) {
// logs the entry metadata
console.log(entry.sys)
// logs the field with ID title
console.log(entry.fields.channelName)
})
}
Then I created a test (getContent.test.js) like this:
'use strict';
let chai = require('chai');
let should = chai.should();
var expect = chai.expect;
var rewire = require("rewire");
let getContent = rewire("./getContent.js");
describe('Retreive existing', () => {
it('it should succeed', (done) => {
getContent.getEntry({contentName:'****'
}, undefined, (err, result) => {
try {
expect(err).to.not.exist;
expect(result).to.exist;
// res.body.sould be equal
done();
} catch (error) {
done(error);
}
});
});
});
but I obtain this error:
Retreive existing (node:42572) UnhandledPromiseRejectionWarning:
Error: Request failed with status code 400
at createError (/Users/ire/Projects/SZDEMUX_GDPR/api/node_modules/contentful/dist/contentful.node.js:886:15)
at settle (/Users/ire/Projects/SZDEMUX_GDPR/api/node_modules/contentful/dist/contentful.node.js:1049:12)
at IncomingMessage.handleStreamEnd (/Users/ire/Projects/SZDEMUX_GDPR/api/node_modules/contentful/dist/contentful.node.js:294:11)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) (node:42572) 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(). (rejection id: 3) (node:42572) [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.
Do you know what I'm missing? the promise is ok, I already tested it with a simple node getContent.js
I am seeing few issues with your code:
1. Invalid Args
In your test function, in getContent.js, you are passing an argument to the getEntry method (return client.getEntry('******'), whereas you are passing an object in the test (getContent.getEntry({}))
2. Mixing Promises & Callbacks
it('it should succeed', (done) => {
getContent.getEntry("****")
.then((result) => {
console.log(result);
try {
expect(result).to.exist;
// res.body.sould be equal
done();
} catch (error) {
done(error);
}
})
.catch(error => {
console.log(error);
done(error)
})
});
3. Source of Unhandled Promise rejection is not clear:
Is it coming from your test function in getContent.js, or, is it coming from your actual test?
Probably, this could also come from,
expect(err).to.not.exist;
expect(result).to.exist;
Always catch errors in Promises and reject it with proper reason to avoid issues like this.
Could you please update your code and repost it, so that its clear for other users?

Categories