Discord.js get rank position of user - javascript

I want to get the number of users that have a lower number of XP points than the member who used the command, this way I can get his rank.
However I don't know much in javascript and sql queries, and I'm hard stuck with this, where it simply returns [object Object] instead of a number.
My sql table
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER, level INTEGER, money INTEGER);").run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// And then we have two prepared statements to get and set the score data.
client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level, money) VALUES (#id, #user, #guild, #points, #level, #money);");
});
My attempt
if (message.content.startsWith(prefix + "cl stats")) {
const curxp = score.points;
client.rank = sql.prepare("SELECT count(*) FROM scores WHERE points >= #curxp AND guild = #guild").get();
console.log(client.rank);
await message.reply(`${client.rank}`);
}

Found a solution. Probably not the best but it works.
client.getRank = sql.prepare("SELECT count(*) FROM scores WHERE points >= ? AND guild = ?");
function getRank(){
const curXP = score.points;
let rankOBJ = client.getRank.get(curXP, message.guild.id)
console.log(rankOBJ);
let rankStr = JSON.stringify(rankOBJ);
let rank = rankStr.match(/\d/g);
return rank;
};

Related

select query in MySQL NodeJS

I am making search route for property table where user can enter city, state, street_address , minamount , max_amount to search for different properties. My problem is if user only enter one or two fileds search should be filter by those field only. and if user does not enter any parameters, it should show every property.
const sqlQuery = `SELECT * FROM property WHERE state = ? AND city = ? AND street_address = ? AND min_amount >= ? AND max_amount <= ?; `
const values = [req.body.state, req.body.city, req.body.street_address ,req.body.min_amount,req.body.max_amount];
let data = [];
db.query (sqlQuery, values, function (err, results, fields) {
if (err) {
console.log(err)
}
if (results.length >= 1) {
}
You need to construct your sqlQuery manually by checking the existence of each parameter and appending a corresponding WHERE clause individually for each parameter, if this parameter exists.

MySql query to get all user's conversations and data about user that he is having conversation with

db structure
I am creating simple conversation app. I have three tables - users(id,name), conversations(id,user1_id, user2_id) and messages (id,conversationId,sender,message,date). Is there a way to actually get all user's conversations and data about another user in one query?
The query below gets id's of the user that logged user has conversations with. I would like now to get these users data base on their id. Thanks for all suggestions.
const getChats = (req, res) => {
const userId = req.params.userId;
db.query(
"SELECT DISTINCT CASE WHEN user1_id = ? THEN user2_id ELSE user1_id END userID FROM conversations WHERE ? IN (user2_id , user1_id)",
[userId, userId],
(e, r) => {
res.send(r);
}
);
};
module.exports = { getChats };
First, I'll answer the second question "how can get rid of doubling conversations where only conversation id differs and users are basically swapped?" to resolve this issue you need to check the conversation table before insertion by the below query
db.query(
"SELECT * FROM conversations WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)",
[senderId, receiverId,receiverId,senderId],
(e, r) => {
res.send(r);
}
);
if the above query returns a record then we'll not insert a new row.
now query for message with user data of a conversation
db.query(
"SELECT m.*,c.id,
s.name as "SenderUserName",
r.name as "ReceiverUserName",
FROM messages m
inner join conversations c on m.conversationId = c.id
inner join user r on r.id = c.user1_id
inner join user s on s.id = c.user2_id
WHERE (c.user1_id = ? AND c.user2_id = ?) OR (c.user1_id = ? AND
c.user2_id = ?)",
[senderId, receiverId,receiverId,senderId],
(e, r) => {
res.send(r);
}
);
the above query will return all messages between 2 users.
though you can remove the conservations table from the structure and it will be easy approach, here is the structure that i suggest
users table
name
type
id
int
name
varchar
messages table
name
type
id
int
message
text
sender_id
int
receiver_id
int
created_at
timestamp

How to get all elements even if they have the same data

I have a project where I would like to gather in all brandname and price from a site.
for that reason I have the following code:
List<WebElement> list_of_products = driver.findElements(By.xpath(loc.getProperty("brandName")));
List<WebElement> list_of_products_price = driver.findElements(By.xpath(loc.getProperty("finalPrice")));
//System.out.println("ezek a termékek"+ list_of_products);
// Use of HashMaop to store Products and Their prices(after conversion to
// Integer)
String product_name;
String product_price;
int int_product_price;
HashMap<Integer, String> map_final_products = new HashMap<>();
{
for (int i = 0; i < list_of_products.size(); i++) {
product_name = list_of_products.get(i).getText();// Iterate and fetch product name
product_price = list_of_products_price.get(i).getText();// Iterate and fetch product price
product_price = product_price.replaceAll("[^0-9]", "");// Replace anything will space other than numbers
int_product_price = Integer.parseInt(product_price);// Convert to Integer
map_final_products.put(int_product_price, product_name);// Add product and price in HashMap
}
// write out all the products we found
Reporter.log("All the prices and products we found: " +
map_final_products.toString()+ "\n", true);
// Get all the keys from Hash Map
Set<Integer> allkeys = map_final_products.keySet();
ArrayList<Integer> array_list_values_product_prices = new ArrayList<Integer>(allkeys);
// this will sort in ascending order lowest at the top and highest at the bottom
Collections.sort(array_list_values_product_prices);
As it is on console:
XYs are the actual brandnames
All the prices and products we found: {20720=XY,
11490=XY, 13490=XY, 15490=XY,
19490=XY, 21990=XY, 16490=XY, 18490=XY
20490=XY, 18990=XY, 20990=XY}
As I think my code just does not write out or collect when the price is the same with other brands(or with the same brands too). For example:
At the website there are more products for 13490.. and lots of for 18490.
How can I modify my code in order to get all the pairs even if they have same prices?
#Peter Santa, you should have product Name as your key instead of Price. So you can reverse the location. But this will not print the same product with the same or different price. Which I feel should be ok assuming, the same product will not have different prices on the same website.

Building velo query function to sum total values from multiple datasets

Thank you for looking at thus question. It's driving me crazy.
I have 2 databases with various fields which are:
dataset = projectproducts
field ID = product // matching ID in products dataset
field ID = productQuantity // returns number
dataset = products
field ID = _id // matching product field value in projectproducts
field ID = productPrice // returns number
I am trying to query the projectproducts dataset and retrieve the items from the product field (several hundred of them) and the quantity from the productQuantity field.
Then based on the product field (which is the ID of the item/row in the products dataset) query the products dataset and retrieve the result from productPrice field.
Then I'd like to multiply the
productQuantity result x productPrice result
and add all the values together to retrieve a final amount.
I'm not sure about how it's different when datasets are involved but here is an approach which uses wixData directly
import wixData from 'wix-data';
$w.onReady(async function () {
const {items: projectproducts} = await wixData.query('projectproducts').find();
const projectproductsQuery = wixData.query('products');
projectproducts.forEach(pp => {
projectproductsQuery.eq('_id', pp.product)
})
const {items: products} = await projectproductsQuery.find();
const productsPrices = products.reduce((acc, current) => ({
...acc,
[current._id]: current.price
}), {});
console.log({products, productsPrices, projectproducts});
const sum = projectproducts.reduce((acc, current) => {
return acc + productsPrices[current.product] * current.productQuantity;
}, 0);
console.log(sum);
});
Demo: https://moshef9.wixsite.com/agg-collections (Open the console for more information about the collections)

Knex migration fails with - SAVEPOINT can only be used in transaction blocks

I am trying to create a knex migration. The migration should be a transaction that should add role and some users to database. If the users are already in db the transaction should change their role_id to new role_id
exports.up = function(knex) {
async function transaction(t) {
await t.raw('INSERT INTO "public"."role" VALUES (3, \'external_support\');');
let i;
for(i = 0; i < newUsers.length; i += 1) {
const result = await t.raw('SELECT id FROM "public"."user" WHERE email = ?;', [
newUsers[i].email
]);
if (result.rowCount === 0) {
await t.raw('INSERT INTO "public"."user" (email, first_name, last_name) VALUES (?, ?, ?);', [
newUsers[i].email,
newUsers[i].firstname,
newUsers[i].lastname
]);
await t.raw('INSERT INTO "public"."users_roles" VALUES ((SELECT id FROM "public"."user" WHERE email = ?) , 3);', [
newUsers[i].email
]);
} else {
await t.raw('UPDATE "public"."users_roles" SET role_id = 3 WHERE user_id = (SELECT id FROM "public"."user" WHERE email = ?);', [
newUsers[i].email
]);
}
}
}
So basic logic behind this is (should be)
- add new role
- check whether users exist
- If not add users and set their role_id to new
- If yes then change their role_id to new
So, what I get is
`error: SAVEPOINT can only be used in transaction blocks`
Why?
The issue here was that I did not pay attention to documentation. I know I had seen this but I totally forgot.
By default, each migration is run inside a transaction.
So creating the transaction in transaction will lead to fussy behavior. In this case that was double committing.

Categories

Resources