I'm trying to add more than one into this switch thing, it works with one, but adding more just adds gets me this error "interaction is not defined"
game1 & network is querying to
const { game1db, networkdb} = require('../mysql/mysqlquery.js')
How do I solve this "interaction is not defined", I'd be grateful for all the help
Code:
const run = async (client, interaction) => {
if (!interaction.guild) return;
let platform = interaction.options.get('platform').value
let username = interaction.options.getString("username")
console.log(platform)
const hasRole = interaction.member.roles.cache.some(r => r.name === "Support")
if (!hasRole) return;
await interaction.deferReply({ ephemeral: true });
await wait(4000);
switch (platform) {
case "network":
try {
networkdb(`${username}`, (err, result) => {
if (err) {
interaction.followUp({ content: result, ephemeral: true });
} else {
interaction.followUp({ content: result, ephemeral: true });
}
})
} catch (error) {
interaction.followUp({ content: `error: ${error}`, ephemeral: true });
}
break;
case "game1":
try {
game1db(`${username}`, (err, result) => {
if (err) {
interaction.followUp({ content: result, ephemeral: true });
} else {
interaction.followUp({ content: result, ephemeral: true });
}
})
} catch (error) {
interaction.followUp({ content: `error: ${error}`, ephemeral: true });
}
break;
default:
interaction.followUp({ content: `${platform} is not supported yet`, ephemeral: true });
}
}
Related
I've got an app that connects to a SQL Server database. It has 3 post API's that are going to get A LOT of traffic. I'm having trouble with connection timeout and want to make sure I have Connection Pooling setup correctly or figure out where I'm going wrong. I have a DBConfig.js file setup as follows
var sql = require('mssql');
let curacaopool = null;
const curacao = () => {
let config;
if (null !== curacaopool) {
return curacaopool;
}
if (process.env.APP_ENV === 'prod') {
config = {
user: 'user',
password: 'password',
server: 'IP Address',
port: 51678,
database: 'Database',
connectionTimeout: 15000,
//requestTimeout: 45000,
pool: {
max: 10,
min: 1,
idleTimeoutMillis: 30000
}
};
}
curacaopool = new sql.ConnectionPool(config).connect();
return curacaopool;
};
module.exports = { curacao };
My API's are setup as follows. I have 3 of them. The first API gets called and returns an ID then the next two API's get called
APIs
var express = require('express');
var router = express.Router();
var sql = require('mssql');
const { curacao } = require('../../../repository/getDbConfig');
router.post('/workstation', async function (req, res, next) {
curacao()
.then((pool) => pool.request())
.then((request) => {
for (const [key, value] of Object.entries(dbColumns)) {
if (typeof value !== 'undefined' && value !== '') {
request.input(key, dbTypes[key], value);
}
}
request.input('ip_address', sql.VarChar, ip_address);
request.output('workstationId', sql.Int);
request.execute('Gumshoe.dbo.InsertWorkstations', (err, result) => {
if (err) {
res.status(500).json({ 'Workstation Error': err });
}
res.status(200).json({
status: 200,
message: 'Data Saved',
workstationId: result.output.workstationId
});
});
})
.catch((err) => {
console.log('Workstations Error', err);
res.status(500).json({ 'Workstations Error': err });
});
});
router.post('/packages', async function (req, res, next) {
const sentdata = req.body;
var table = new sql.Table('Database.dbo.Packages');
table.create = false;
table.columns.add('workstation_id', sql.Int, { nullable: true });
table.columns.add('pkg_name', sql.VarChar, { nullable: true });
table.columns.add('pkg_ver', sql.VarChar, { nullable: true });
table.columns.add('appWizName', sql.VarChar, { nullable: true });
table.columns.add('appWizPublisher', sql.VarChar, { nullable: true });
table.columns.add('appWizInstalledOn', sql.Date, { nullable: true });
table.columns.add('appWizVersion', sql.VarChar, { nullable: true });
table.columns.add('appWizSize', sql.VarChar, { nullable: true });
table.columns.add('customTrack1', sql.VarChar, { nullable: true });
table.columns.add('customTrack2', sql.VarChar, { nullable: true });
table.columns.add('customTrack3', sql.VarChar, { nullable: true });
if (sentdata.length > 0) {
sentdata.forEach((item) => {
if (parseInt(item.workstation_id) > 0 && item.pkg_name.length > 1) {
return table.rows.add(
item.workstation_id,
item.pkg_name,
item?.pkg_ver || null,
item?.appWizName || null,
item?.appWizPublisher || null,
item?.appWizInstalledOn ? (dateCheck(item.appWizInstalledOn) === true ? item.appWizInstalledOn : null) : null,
item?.appWizVersion || null,
item?.appWizSize || null,
item?.customTrack1 || null,
item?.customTrack2 || null,
item?.customTrack3 || null
);
}
});
curacao()
.then((pool) => pool.request())
.then((request) =>
request
.bulk(table, (err, result) => {
if (err) {
console.log('Package Bulk Error:', err);
res.status(500).json({ 'Bulk Packages': err });
}
res.status(200).json(result);
})
.catch((err) => {
console.log('Packages Error', err);
res.status(500).json({ 'Packages Error': err });
})
);
} else {
console.log('Package sent data was empty Array', sentdata);
res.status(500).send('Package empty Array');
}
});
The first API calls a stored proc, this stored proc deletes data from the tables for the next two APIs. The next two (both setup the same) do Bulk Inserts to two other tables
I'm having a lot of trouble with Timeout Errors
Webserver
returned:{"status":500,"pool_error":{"code":"ETIMEOUT","originalError":{"message":"Timeout:
Request failed to complete in 15000ms
I've tried increasing the pool Max to 25. I've tried increased the requestTimeout value. Both of those haven't worked or helped. These work in test when not under heavy load so wondering what I look to next to get this resolved.
Thanks for any assistance
this is my schema.it has a user field and an array of object which contains a text message and direction will hold a either sent or received value.
const MessageSchema = new mongoose.Schema({
user:{type: String,required: true},
textArray:[
{
text:{type: String,required: true},
direction:{ type: String,required: true }
}]
});
This is the router code.btw should there be double quotes on the keys in var textmessage?
router.post('/',async(req,res)=>{
const {user,text,direction}=req.body;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
var textmessage={
"text":text,
"direction":direction
}
const doc = await Message.updateOne(
{ user: user },
{ $set: { user:user,$push:{textArray:textmessage}} },
{ upsert: true },
function(err,result){
if (err){
console.log(err);
}
else{
console.log(result)
res.send(result)
}// Make this update into an upsert
});
})
this is how it showsup in mongodb.the user is working ok but when i click theres is nothing under textArray.What am I doing wrong exactly?
you are using await with callback function , which is wrong :
const filter = { user: user };
const update = { $push:{textArray:textmessage}};
let doc = await Message.findOneAndUpdate(filter, update, {
new: true,
upsert: true
});
console.log('doc=',doc);
i have a product profile, and when i want to edit the product, i would like that the user can, Edit fields in the producto (title, price....), upload a new image, and delete some image. All of this at the same time, in the same operation.
I have this code, that works but not at all.
const producto = await Producto.findByIdAndUpdate(
req.params.id,
{
'$pull': {"images": {"filename": imagesDelete }},
'$set': {title, categoria, subCategoria, price, description, contacto}},
{new: true}
);
with this code i can: upload an image and edit form, upload an image and delete some image. But when i want to upload image, delete image, and edit form. Not works....
Someone can tell why?
Here is the complete code in the editProduct:
exports.editarProductoUser = async (req, res, next) => {
//REVISAR SI HAY ERRORES
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
console.log(req.body);
const { imagesDelete, title, categoria, subCategoria, price, description, contacto } = req.body;
try {
// //REVISAR EL ID
const productoTest = await Producto.findById(req.params.id);
// //SI EL PRODUCTO EXISTE O NO!!!
if (!productoTest) {
console.log("hay un error en edicion");
return res.status(404).json({ msg: "Producto no encontrado" });
}
// // //Verificar el PRODUCTO
if (productoTest.author.toString() !== req.user.id) {
return res.status(401).json({ msg: "No Autorizado para Editar" });
}
if (imagesDelete !== undefined) {
if (typeof imagesDelete === "string") {
cloudinary.uploader.destroy(imagesDelete, function (err, res) {
if (err) {
console.log(err);
return res.status(400).json({
ok: false,
menssage: "Error deleting file",
errors: err,
});
}
console.log(res);
});
} else {
for (let filename of imagesDelete) {
console.log(filename);
cloudinary.uploader.destroy(filename, function (err, res) {
if (err) {
console.log(err);
return res.status(400).json({
ok: false,
menssage: "Error deleting file",
errors: err,
});
}
console.log(res);
});
}
}
}
//ACTUALIZAR PRODUCTO
const producto = await Producto.findByIdAndUpdate(
req.params.id,
{
'$pull': {"images": {"filename": imagesDelete }},
'$set': {title, categoria, subCategoria, price, description, contacto}},
{new: true}
);
const images = req.files.map((f) => ({
url: f.path,
filename: f.filename,
}));
//if(producto.images === undefined) return null;
producto.images.push(...images);
console.log(producto.images);
await producto.save();
res.json({ producto });
} catch (error) {
console.log(error);
res.status(500).send("Hubo un Error");
}
};
Here a snapshot of the form, to see the fields:
$pull and $set
db.collection.update({
_id: "123"
},
{
"$pull": {
images: {
filename: "123"
}
},
"$set": {
title: "banana",
categoria: "b",
price: 200
}
})
mongoplayground
nodejs mongoose
let query = {
_id: "123"
};
let update = {
"$pull": {
"images": {
"filename": "123"
}
},
"$set": {
"title": "banana",
"categoria": "b",
"price": 200
}
};
Producto.updateOne(
query,
update,
function(err, result) {
if (err) {
...
} else {
...
}
}
);
I would like to update the shipping property in my MongoDb (CRUD).
Shipping is an array property that contains object[index]. How to update the specific object such as index1 or index2.
This show the shipping property that contains two objects
If I want to update Object only at index 1 on the providerName, how can I do that
exports.updateShpping = (req, res) => {
const {shipping} = req.body;
Shop.findOne({ _id: req.shop._id }, (err, shop) => {
if (!shipping) {
return res.status(400).json({
error: 'shipping is required'
});
} else {
shop.shipping.push(shipping) ;
}
shop.save((err, addShipping) => {
if (err) {
console.log('Shipping ADD ERROR', err);
return res.status(400).json({
error: 'Shipping add failed'
});
}
res.json(addShipping);
});
});exports.updateShpping = (req, res) => {
const {shipping} = req.body;
Shop.findOne({ _id: req.shop._id }, (err, shop) => {
if (!shipping) {
return res.status(400).json({
error: 'shipping is required'
});
} else {
shop.shipping.push(shipping) ;
}
shop.save((err, addShipping) => {
if (err) {
console.log('Shipping ADD ERROR', err);
return res.status(400).json({
error: 'Shipping add failed'
});
}
res.json(addShipping);
});
});
};
I'm trying to figure out how to add an if/else here so that if classroomId has a value, the importUserToClassroom endpoint will be hit. If not, I'd like to execute the same code, but with the importUsers endpoint. Any ideas on where I'm going wrong with my syntax would be much appreciated!
handleFormSubmit(data) {
const {
importUserToClassroom,
importUsers,
addFlashMessage,
formatErrors,
showUiBlocked,
hideUiBlocked,
match: {params: {classroomId}},
} = this.props;
showUiBlocked();
const users = userDataToList(data);
{
classroomId !== undefined ? (
importUserToClassroom({
users,
classroomId,
})
) : (
importUsers({users})
)
}
.then(() => {
hideUiBlocked();
addFlashMessage('Users imported successfully', 'success');
this.context.router.history.push('/users');
})
.catch(err => {
hideUiBlocked();
if (err.status !== 409) {
return formatErrors(err).then(err => {
this.setState({
errors: err,
});
});
} else {
this.setState({
errors: {
usernames: err.data.message,
}
});
}
});
}
Update: The following ended up working!
handleFormSubmit(data) {
const {
importUserToClassroom,
importUsers,
addFlashMessage,
formatErrors,
showUiBlocked,
hideUiBlocked,
match: {params: {classroomId}},
} = this.props;
showUiBlocked();
const users = userDataToList(data);
if (!isEmpty(classroomId)) {
importUserToClassroom({
users,
classroomId,
})
.then(() => {
hideUiBlocked();
addFlashMessage('Users imported successfully', 'success');
this.context.router.history.push('/users');
})
.catch(err => {
hideUiBlocked();
if (err.status !== 409) {
return formatErrors(err).then(err => {
this.setState({
errors: err,
});
});
} else {
this.setState({
errors: {
usernames: err.data.message,
}
});
}
});
} else {
importUsers({users})
.then(() => {
hideUiBlocked();
addFlashMessage('Users imported successfully', 'success');
this.context.router.history.push('/users');
})
.catch(err => {
hideUiBlocked();
if (err.status !== 409) {
return formatErrors(err).then(err => {
this.setState({
errors: err,
});
});
} else {
this.setState({
errors: {
usernames: err.data.message,
}
});
}
});
}
}
This isn't really JSX, but you do have some syntax errors. You can't use curly brackets like that. If importUserToClassroom and importUsers return promises, you could try something like this:
const savePromise = classroomId ?
importUserToClassroom({
users,
classroomId,
}) :
importUsers({users});
savePromise.then(() => {
hideUiBlocked();
addFlashMessage('Users imported successfully', 'success');
this.context.router.history.push('/users');
})