Module not found: Can't resolve 'pg-native' - database

I am trying to make a simple user login, and I want to store the hash and salt in a PostgreSQL database.
const {Client} = require("pg");
const bcrypt = require('bcrypt');
const client = new Client({
user:"xxxxxxx",
host:"xxxxxxxxxxxxxxxxxx",
database:"xxxxxxxxx",
password:"xxxxxxxxxxxxxxxxxxxxxxx",
port: 1234
});
client.connect()
const saltRounds: number = 10;
const newUserHash = (username: String, password: String) => {
bcrypt.genSalt(saltRounds, function(err: Error, salt: String) {
bcrypt.hash(password, salt, function(err: Error, hash: String) {
//send it to database
});
});
}
But I keep getting this error; Module not found: Can't resolve 'pg-native'. Using import pg from 'pg' has not worked for me and I don't know what to do anymore.

Related

POST https://ipfs.infura.io:5001/ipfs/api/v0/add?stream-channels=true&progress=false 403 (Forbidden). HTTPError: ipfs method not supported

Below is how i create the client.
import { create as ipfsHttpClient } from 'ipfs-http-client';
const projectId = 'xx';
const projectSecret = 'xx';
const auth = `Basic ${Buffer.from(`${projectId}:${projectSecret}`).toString('base64')}`;
const options = {
host: 'ipfs.infura.io',
protocol: 'https',
port: 5001,
apiPath: '/ipfs/api/v0',
headers: {
authorization: auth,
},
};
const dedicatedEndPoint = 'https://xx.infura-ipfs.io';
const client = ipfsHttpClient(options);
Here is the function that will be called from front-end that takes in a file, uploads to IPFS and returns URL. Please note that the "ipfsHTTPClient()" is just the create function.
const uploadToIPFS = async (file) => {
try {
const added = await client.add({ content: file });
const url = `${dedicatedEndPoint}${added.path}`;
return url;
} catch (error) {
console.log('Error uploading file to IPFS: ', error);
}
};
The error I am getting is
POST https://ipfs.infura.io:5001/ipfs/api/v0/add?stream-channels=true&progress=false 403 (Forbidden)
When i console log the error it says the IPFS method is not supported.
On the IPFS forum, i have seen someone say that add function does not work anymore but i have also seen people using it and it working. Im not sure whats wrong here.
Here is how i call the function on front-end
const { uploadToIPFS } = useContext(NFTContext);
// function called from useDropzone
const onDrop = useCallback(async (acceptedFile) => {
const url = await uploadToIPFS(acceptedFile[0]);
setFileUrl(url);
}, []);
All the above code is correct and the error was from Next.js
Needed to add
images: {
domains: ['xx.infura-ipfs.io'],
},
to the next.config.js file.
I have resolved this problem
so make sure first you have installed buffer
npm install --save buffer
then import it in your file
import {Buffer} from 'buffer';
then it works successfully
import { create } from "ipfs-http-client";
import { Buffer } from "buffer";
const projectId = "YOUR_INFURA_PROJECT_ID";
const projectSecret = "YOUR_INFURA_PROJECT_SECRET";
const auth = `Basic ${Buffer.from(`${projectId}:${projectSecret}`).toString(
"base64"
)}`;
const client = create({
host: "ipfs.infura.io",
port: 5001,
protocol: "https",
apiPath: "/api/v0",
headers: {
authorization: auth,
},
});
const uploadFiles = async (e) => {
e.preventDefault();
setUploading(true);
if (text !== "") {
try {
const added = await client.add(text);
setDescriptionUrl(added.path);
} catch (error) {
toast.warn("error to uploading text");
}
}

Number Type Schema not updating

I'm trying to make a bot that let's you give fame points to users as well as currency, currency works just fine and it updates whenever someone sends a message with a 1 minute cooldown. however I'm having problems with my fame schema. the bot creates a new schema if there's not an already existing one without problem and it also displays the amount correctly, however, when you click the button to give someone a Fame point, it doesn't, it stays at 0. I'm probably missing something simple but I can't seem to find it, here's the code:
const { MessageEmbed,ButtonInteraction} = require('discord.js');
const Fame = require('../../schemas/fame');
module.exports = {
data: {
name: `yes-fame`
},
async execute (interaction, client) {
const user = require('../../commands/entertainment/givefame')
const fameProfile = await client.createFame(user)
try {
await Fame.findOneAndUpdate({ _id: fameProfile._id}, { $inc: { amount: 1 } });
} catch (error) {
console.log(error);
}
const userEmbed = new MessageEmbed()
.setTitle(`<:fame:952026535756435536> Fame Point Given`)
.setDescription(`${interaction.user} has given 1 fame point to ${user} `)
.setTimestamp()
.setColor("#00FF00")
.setFooter(client.user.tag, client.user.displayAvatarURL());
await interaction.reply({ embeds: [userEmbed]});
}
};
(the cooldown is low because I'm not entirely sure how long to make it yet)
Here is the code for the Fame Schema.
const mongoose = require('mongoose');
const fameSchema = new mongoose.Schema ({
_id: mongoose.Schema.Types.ObjectId,
guildId: String,
memberId: String,
amount: { type: Number, default: 0}
});
module.exports = mongoose.model('Fame', fameSchema, 'fame-points');
and here's the code for the const "user", it's either the user mentioned or if none, the one using the slash command.
const user = interaction.options.getUser("user") || interaction.user;
And here's the createFame function
const Fame = require('../schemas/fame');
const mongoose = require('mongoose');
module.exports = (client) => {
client.createFame = async (member) => {
let fameProfile = await Fame.findOne({ memberId: member.id, guildId: member.guild.id });
if (fameProfile) {
return fameProfile;
} else {
fameProfile = await new Fame({
_id: mongoose.Types.ObjectId(),
guildId: member.guild.id,
memberId: member.id,
});
await fameProfile.save().catch(err => console.log(err));
return fameProfile;
}
};
};
I thought that maybe there was an error in the user const itself or when importing it but I made the bot send a test message using that const and it is getting the user no problem so idk what's wrong.
it shows the error:
TypeError: Cannot read properties of undefined (reading 'id')
at Client.client.createFame (C:\Users\xxx\OneDrive\desktop\bot\src\functions\createFame.js:6:89)
at Object.execute (C:\Users\xxx\OneDrive\desktop\bot\src\buttons\info\yes-fame.js:10:46)
at Object.execute (C:\Users\xxx\OneDrive\desktop\bot\src\events\interactionCreate.js:25:26)
at Client. (C:\Users\xxx\OneDrive\desktop\bot\src\functions\handleEvents.js:8:58)
There is a $inc property/method/wtv in mongoose model. Try this-
await Fame.findOneAndUpdate({ _id: fameProfile._id}, { $inc: { amount: 1 } });

Discord.js: Export Ban list command not working

I recently started working on discord ban bot with 3 main features:
Export IDs of all banned users in current Server/Guild.
Import IDs of banned users into current guild
Transfer ban list from current server to target server. (Under development)
None of the slash commands are working even though the logic is seemingly correct.
I'm following the discordjs guide & managed to make a Time Tag generator bot & this is my 2nd bot project. I admit I'm not familier with Javascript but the guide is very helpful nonetheless
Here is the export-ban-list code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
function new_paste(serverName, results) {
const outputFile = `${serverName}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return data;
}
else {
return 'There was some unexpected error.';
}
});
}
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
const fe = new_paste(interaction.serverName, results);
return interaction.editReply(fe);
},
};
This command basically calculates the number of users banned, makes an array & exports it to pastebin.
The issue is, the bot code reaches till calculation part, but when it comes to making the list, console throws me errors:
Found 13 bans. Exporting...
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async InteractionWebhook.editMessage (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\Webhook.js:311:15)
at async CommandInteraction.editReply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:137:21)
at async Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:41:3) {
method: 'patch',
path: '/webhooks/897454611370213436/aW50ZXJhY3Rpb246ODk4ODkyNzI0NTcxMzczNjA5OmtPeGtqelQ5eUFhMnNqVzc1Q3BpMWtQZUZRdVhveGQxaHFheFJCdVFoUWNxNUk5TVpGbThEQjdWcDdyaHZyaUJPeUpsRWFlbUp0WnVLYjB5V0RtYmJCSmlNU2wwUVlka1hYMHg0bHRJbzlHelVwRmJ6VUpRaXF2YktaVDN1ZlVp/messages/#original',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at CommandInteraction.reply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89:46)
at Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:45:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
Thanks to Jim I used the console.log() to check what was going on.
And indeed the data from function inside new_paste() wasn't being returned to fe.
(I had messed up the return scopes basically)
Here is the final code after fixes & scope resolutions
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
console.log(results);
const outputFile = `${interaction.guild.name}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return interaction.editReply(data);
}
else {
return interaction.editReply('There was some unexpected error.');
}
});
},
};
And finally I get the proper pastebin url as output.
Code hosted here
I think your npm package better-pastebin has an error. I am not familiar with that npm package, so I can’t determine whether it has an error for you, but I think if you change the npm package, the error will not appear.

ReactJS Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid

I'm getting the following error in my react application using enigma.js (https://qlik.dev/apis/javascript/enigmajs) . I'm trying to initialize a WebSocket connection and im getting the error. "Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid".
The WebSocket connection URL is correct as it can be tested with https://catwalk.core.qlik.com/?engine_url=wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde which returns the data. You can try by editing the URL which will return an error.
the code is
async init() {
const appId = "133dab5d-8f56-4d40-b3e0-a6b401391bde";
const url =
"wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde";
const session = enigma.create({
schema,
createSocket: () =>
new WebSocket(url, {
}),
});
const global = await session.open();
const app = await global.openDoc(appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
I found the solution:
qDoc.config.js
const enigma = require('enigma.js');
const schema = require('enigma.js/schemas/12.20.0.json');
const SenseUtilities = require('enigma.js/sense-utilities');
const config = {
host: 'sense-demo.qlik.com',
secure: true,
port: 443,
prefix: '',
appId: '133dab5d-8f56-4d40-b3e0-a6b401391bde',
};
const url = SenseUtilities.buildUrl(config);
async function init() {
const session = enigma.create({
schema,
url,
suspendOnClose: true,
});
const global = await session.open();
const app = await global.openDoc(config.appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
init();
const session = enigma.create({ schema, url, suspendOnClose: true });
// open doc and return promise which will resolve to doc
export const openDoc = () => (
session.open().then((global) => global.openDoc(config.appId))
);
// close session
export const closeSession = () => (
session.close()
);
INSTURCTION
downoad this project
delete package-lock.json file
npm i
npm run-script dev
This is the direvtory view:
This is result log:
The solution is explained here
https://github.com/qlik-oss/enigma.js/issues/889

I'm trying to query MySQL as a promise, but I keep getting "unhandledpromiserejection error"

Please help I'm trying to deploy my app to App Engine/CloudSQL but I keep getting :
"UnhandledPromiserejectWarning": Cannot enqueue after fatal error..
I'm trying to query MySQL as promise, when I don't I handle the exception it works fine locally, but when I deploy it doesn't work.
How can I handle promise rejection, please Help Thanks
This is db.js
const db = require('./Mysql')
const query = (q, data) => {
return new Promise((resolve, reject) => {
db.query(q, data, (err, res) => (err ? reject(err) : resolve(res)))
})
.then(res => console.log(res))
.catch(err => console.error(err))
This is Mysql.js
{ SQL_SOCKET, SQL_USER, SQL_PASSWORD, SQL_DATABASE } = process.env
const db = mysql.createConnection({
socketPath: SQL_SOCKET,
user: SQL_USER,
password: SQL_PASSWORD,
database: SQL_DATABASE,
charset: 'utf8mb4',
})
module.exports = db
I remember having this problem a few years ago when I tried using the mysql module within an expressJS application and attempted to use async/await. The error could also come from querying on a connection in which a fatal error occured, see here. As such, best practices dictates that on queries, you open a connection, start a query transaction, commit the query and then release the connection afterwards -- allowing you to rollback whenever an error occurs. I do not see this process happening here so it could be a possibility.
In any case, I can provide you with an alternative, which is the method I ended up going with. Basically, I digressed promisifying query() myself and instead let node handle it.
An example of using query without transaction:
/backend/database/database.js
const mysql = require('mysql');
const db = require('../config/config').mysql;
const util = require('util');
const pool = mysql.createPool({
connectionLimit: require('../config/config').cLimit,
host: db.host,
user: db.user,
password: db.password,
database: db.database
});
pool.query = util.promisify(pool.query);
async function query(cmd) {
try {
let result = await pool.query(cmd);
return result;
} catch(error) {
console.error(error);
}
}
module.exports = {
query
};
Which can then be used in your models like such:
/backend/models/User.js
const db = require('../database/database');
async function getUserById(userId) {
const cmd = `SELECT * FROM Users WHERE userId = ${userId}`;
try {
let result = await db.query(cmd);
return result;
} catch(error) {
throw {
message: error
}
}
}
module.exports = {
getUserById
};
Which in turn, can be called from your route handler like such:
/backend/routes/users.js
const router = require('express').Router();
const User = require('../models/User');
router.get('/getUserById/:userId', async (req, res) => {
try {
let user = await User.getUserById(req.params.userId);
res.status(200).send({ user });
} catch(error) {
console.error(error);
res.status(400).send({ error: 'Unable to fetch user' });
}
});
module.exports = router;

Resources