I get Parser.parseErrorMessage when inserting or updating in postgres - node.js

i'm having a headache with this cause i can't understand what's the problem.
This is my code in Express
router.patch("/:id", verifyToken, async (req, res) => {
const { id } = req.params;
const { title, content, categories } = req.body;
const authorId = parseInt(req.user.id);
try {
let postId = parseInt(id);
if (postId < 0)
res.json(
utils.generateError("Something went wrong, try to reload the page.")
);
//Validate post data
const { error } = validatePostData({
title,
content,
});
//Is there and error? Let the user know it.
if (error)
res.status(400).json(utils.generateError(error.details[0].message));
const slug = await utils.generateSlug(title);
const summary = await utils.extractSummary(content, 240);
const foundImage = await content.match(/!\[.*?\]\((.*?)\)/);
let image = "";
if (foundImage) image = foundImage[1];
const result = await pool.query(
"UPDATE posts SET title=$1, slug=$2, summary=$3, content=$4, image=$5, author=$6, categories=$7 WHERE id=$8",
[title, slug, summary, content, image, authorId, categories, postId]
);
if (result) res.json(result.rows[0]);
else throw "Error on updating result";
} catch (e) {
console.log(e);
res.json(utils.generateError("Something went wrong, try again."));
}
});
But when i make a patch request i get this in the console.
(node:20756) UnhandledPromiseRejectionWarning: error: invalid input syntax for integer: "NaN"
at Parser.parseErrorMessage (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/index.js:8:42)
at Socket.emit (events.js:310:20)
at addChunk (_stream_readable.js:286:12)
at readableAddChunk (_stream_readable.js:268:9)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
(node:20756) 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:20756) [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 using Postgres and pg for node to handle the database, the strange part is that the row is updated in the db but the result of the query doesn't return anything but that error.
Can anyone help me solve this?

Related

Unsure how to connect an api using nodejs

I'm trying to connect the openai api into my app but I'm not sure why it's not working. From my frontend, I have a createUserData that receives an input and then stores it to my MongoDB database. But now, I want to send that input that I received to the openai API and get a response based on what they said. I tried implementing it here but it crashed on me with this error:
UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
at createError (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (events.js:387:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17844) 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:17844) [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.
For some reason I crash when I try and call this API, am I doing it wrong?
Right now I just want to log whatever the response I get from the API, once I'm able to do that then I will store it to the database as well. But I can't even log it as I get an error. Here is my code:
const { Configuration, OpenAIApi } = require("openai");
// create new user data
const createUserData = async (req, res) => {
const {id, scores, transcript} = req.body
const user_id = req.user._id
console.log(user_id)
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Provide personal feedback for me and give me tips: " + transcript,
temperature: 0.7,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
const newUserData = new UserData({
id: id,
scores: scores,
transcript: transcript,
user_id: user_id
})
// add doc to db
try {
await newUserData.save()
} catch (error) {
res.status(400).json({error: error.message})
}
console.log('POST:', newUserData)
return res.status(201).json({user_data: newUserData})
}

I have a problem with my Discord bot (Minecraft server status bot)

This is the index.js script of the bot:
const { Client, RichEmbed } = require('discord.js')
const bot = new Client()
const util = require('minecraft-server-util')
const token = 'bot_token'
const PREFIX = 'l.'
bot.on('ready', () => {
console.log('Bot has come online.')
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(' ')
switch (args[0]) {
case 'status':
util.status('IP', (PORT), (error, reponse) => {
if (error) throw error
const Embed = new RichEmbed()
.setTitle('Server Status')
.addField('Server IP', reponse.host)
.addField('Server Version', reponse.version)
.addField('Online Players', reponse.onlinePlayers)
.addField('Max Players', reponse.maxPlayers)
message.channel.send(Embed)
})
break
}
})
bot.login(token)
When I type node . in the console and I type l.status on the Discord server, it shows this error on the console:
(node:3300) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'options' to
be an object or undefined, got number
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:46:25
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:4:12)
at status (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:40:12)
at Object.<anonymous> (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:113:17)
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3300) 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:3300) [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.
Can anybody help? I also tried a lot of different solutions, but none of them worked.
You are using an outdatet version of discord.js. Type npm i discord.js#latest into your terminal. In the latest version of discord.js, RichEmbed() has been removed and replaced by MessageEmbed().
This is an answer based on assumption since I've never used minecraft-server-util before. Also assuming that you're using the latest minecraft-server-util,
Based on the error;
Expected 'options' to be an object or undefined, got number
And, based on this commit, You should pass the 2nd argument as an object instead of PORT since it's a type of StatusOptions instead of a number.
So, instead of;
util.status('IP', (PORT), (error, reponse) => {
You should be doing;
util.status('IP', {
port: (PORT)
}, (error, reponse) => {

How to use google-spreadsheet in nodejs

I want to use the google-spreadsheet API to fetch and write data to a sheet in my Discord bot (using discord.js). For some reason, I can't get it to work. This is my code:
const { GoogleSpreadsheet } = require('google-spreadsheet')
const creds = require('../service-account.json')
module.exports = {
/...
execute(message, args) {
accessSpreadsheet()
}
}
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('<id was here>')
doc.useServiceAccountAuth(creds)
.then(() => {
doc.getInfo()
.then(info => {
console.log(`Loaded doc: ` + info.title + ` by ` + info.author.email)
const sheet = info.worksheets[0]
console.log(
`sheet 1: ` + sheet.title + ` ` + sheet.rowCount + `x` + sheet.colCount
)
})
})
}
This is the error I keep getting:
(node:4) UnhandledPromiseRejectionWarning: Error: Google API error - [404] Requested entity was not found.
at createError (/app/node_modules/axios/lib/core/createError.js:16:15)
at settle (/app/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/app/node_modules/axios/lib/adapters/http.js:236:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(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(). 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: 3)
(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 should actually use async/await for achieving this. My code has become:
async function accessSpreadsheet(message, args, msg) {
const doc = new GoogleSpreadsheet('<id was here>')
await doc.useServiceAccountAuth(creds)
await doc.loadInfo()
console.log(doc.title) //whatever you want to log goes here
})

Try to cach UnhandledPromiseRejectionWarning discord.js

i'm trying to catch an discord.js error
This error pops up when internet is off, but i want some clean code instead this messy one...
How can i catch this?
I did really try everything..
code:
(node:11052) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11052) 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 termin
ate the node process on unhandled promise rejection, use the CLI flag `--unhandl
ed-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejecti
ons_mode). (rejection id: 2)
(node:11052) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr
ecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
i did try this at the very top :
process.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
aswell this one :
client.on('error', error => {
if (error.code === 'ENOTFOUND') {
console.log(no internet!!)
}
});
I also did try this to see where its from, but nothing shows up its still the same
try {
var err = new Error("my error");
Error.stackTraceLimit = infinity;
throw err;
} catch(e) {
console.log("Error stack trace limit: ")
console.log(Error.stackTraceLimit);
}
Error stack trace limit:
10
(node:11008) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
here is the code i use for now what gives the error.
i just want to catch the error in something like this: (No connection)
const Discord = require('discord.js')
const client = new Discord.Client({ autoReconnect: true });
const opn = require('opn')
const getJSON = require('get-json')
const request = require('request');
const config = require("./config/config.json");
const pushbullet = require("./config/pushbullet.json");
const addons = require("./config/addons.json");
const Registration = require("./config/Reg.json");
client.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
client.login(config.Settings[0].bot_secret_token);
I would try to wrap it with try/catch.
And maybe add the following code to understand better what is happening.
Error.stackTraceLimit = Infinity
Reference:
https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Microsoft_Extensions/Error.stackTraceLimit
Remember to remove it after the problem solved, this is not suitable for production use.
Well i solved it!!
I put this on top and its all solved.
process.on('unhandledRejection', error => {
if (error.code === "ENOTFOUND") { console.log ("No internet connection")}
if (error.code === "ECONNREFUSED") { console.log ("Connection refused")}
//console.log('Unhandled promise rejection:', error.code);
});

How to show message author avatar adding a user id to the const

i tried to use this code for an avatar command to use even outside servers' ids i can use .avatar #mention || .avatar id but .avatar to show up author's avatar doesn't work there's the error.
(node:9656) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at Object.User (C:\Users\zakaria\Desktop\test1011-master\node_modules\discord.js\src\util\Constants.js:109:16)
at RESTMethods.getUser (C:\Users\zakaria\Desktop\test1011-master\node_modules\discord.js\src\client\rest\RESTMethods.js:406:51)
at Client.fetchUser (C:\Users\zakaria\Desktop\test1011-master\node_modules\discord.js\src\client\Client.js:319:30)
at Client.<anonymous> (C:\Users\zakaria\Desktop\test1011-master\bot.js:963:31)
at Client.emit (events.js:327:22)
at MessageCreateHandler.handle (C:\Users\zakaria\Desktop\test1011-master\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Users\zakaria\Desktop\test1011-master\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:108:65)
at WebSocketConnection.onPacket (C:\Users\zakaria\Desktop\test1011-master\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:336:35)
at WebSocketConnection.onMessage (C:\Users\zakaria\Desktop\test1011-master\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:299:17)
at WebSocket.onMessage (C:\Users\zakaria\Desktop\test1011-master\node_modules\ws\lib\event-target.js:120:16)
(node:9656) 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:9656) [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.
my code:
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === 'avatar') {
const userid = await client.fetchUser(args[0]);
const User = message.mentions.users.first() || userid || message.author ;
const embed = new Discord.RichEmbed()
.setColor('#000000')
.setAuthor(`${User.username}#${User.discriminator}`, User.displayAvatarURL)
.setDescription(`[Avatar Link](${User.avatarURL})`)
.setImage(User.displayAvatarURL)
.setFooter(`Requested By ${message.author.username}#${message.author.discriminator}`, message.author.displayAvatarURL);
message.channel.send(embed);
}
This error originates from this line in the discord.js source:
if (userID.id) userID = userID.id;
userID in this case is passed directly from fetchUser(args[0]). What this means is your args[0] was undefined, but you tried to client.fetchUser(undefined) anyway, and discord.js threw a mysterious error because it didn't check the user input in fetchUser().
To fix you merely need to use a conditional such that you don't try to make invalid requests. I suggest something like this:
if(command === 'avatar') {
const User = message.mentions.users.first() ||
(args[0] && await client.fetchUser(args[0])) ||
message.author;
const embed = ...
}

Resources