Node.js: How to read parameters from an axios get request? - mysql

So I have an axios request along the lines of this in my ReactJS project:
axios.get(URL, {params: {id: id}}
This would pretty much pass a get request to my backend with an URL like so:
URL?id=id
I also have a Node.js Lambda function that runs a mysql query like so:
connection.query("SELECT * FROM database.USER WHERE ID = '"+event.id+"'", function (error, results, fields))
So I know this does not work because I'm passing in a params through a URL, which does not work with event
I am trying to make my Node.js function read the id from my URL params, but I do not seem to know the syntax to do that.
Does anyone know how to get the params from a Node.js function? I've tried stuff like params.id, #id, :id, params[0].id, but none of them seem to work.

First of all you are exposing your backend to SQL Injection. You should NEVER concatenate your sql queries with values from the outside that you don't control. Please read about SQL injection: https://www.w3schools.com/sql/sql_injection.asp
You must use mysql2 library and prepared statements SEE: (https://github.com/sidorares/node-mysql2/blob/master/documentation/Prepared-Statements.md)
Since you are using AWS lambda you read values from the query using:
const id = event.queryStringParameters ? event.queryStringParameters.id : null;

Related

how to make raw sql query on strapi v4 typescript

in strapi v3 you could make a raw sql query the following way:
const data = await strapi.db.connection.raw(`SELECT * from table`);
However, in strapi v4 with typescript enabled, the same line gives the following error:
Property 'connection' does not exist on type 'Database'.
I've searched the documentation but I could not find how to make a custom sql query in strapi 4 with typescript enabled
you can do that exactly the same:
//#ts-ignore
let { rows } = await strapi.db.connection.raw(
`select id from posts where published_at IS NOT null order by random() limit ${count};`
);
sadly the strapi.db.connection does yet not support types, for some reason cannot find this issue, but this prop is Knex prop i'm not entirely sure but you an somehow cast it to Knex

MySQL XDEV Nodejs Driver not returning empty resultset

i'm calling a stored procedure mysql using xdev nodejs driver. The stored procedure returns multiple resultset. When trying nextresultset, i'm getting only the non-empty resultset. So this messes with the resultant data index.
As far as I can understand, the problem is that nextResult() returns false when there are no items in the following result set.
This is an issue in a way that it breaks the following iterator pattern
const res = await session.sql('call proc_with_multiple_and_some_empty_result_sets()').execute()
do {
// do something
} while (res.nextResult())
and does not allow to easily consume the entire result set.
There are workarounds for this, such as using the toArray() method and iterate over the plain data:
res.toArray().forEach(item => {
// do something
})
However, this is a bug, and maybe you can submit a report on https://bugs.mysql.com/ under the Connector for Node.js category.
Disclaimer: I'm the lead dev of the MySQL X DevAPI Connector for Node.js

select distinct values from JSON using django-mysql

I'm using this library and my model looks like this:
class PhoneTest(Model):
data = JSONField()
My JSON obj looks something like this (in a real obj there are way more fields):
{
"deviceStatus": true,
"officerCode": 123456,
"imei": 123456789123456
}
For instance, I want to get a list of all officerCodes. How do I do that ? All I've tried so far has not worked. For example this did not:
tests = PhoneTests.objects.all()
tests.distinct('data__mOfficerCode')
It gives me the following error:
NotSupportedError: DISTINCT ON fields is not supported by this database backend
But it's because I'm using this new library, not the native django mysql backend. What are possible workarounds?
I would greatly appreciate any help.
you can use values_list method
PhoneTests.objects.all().values_list('data__mOfficerCode').distinct()

Get request with query string in express

I want to be able to complete a get request on a local host port. The full url should be "localhost:3000/data/mydb.json?get=somefield" where mydb.json can be any filename and somefield is a key. In my app.js file my get request looks like this:
app.get('/data/:filename?get=somefield', routes.getdatabase);
regardless of what i put in the routes file it is unable to complete a get request on any sort of url matching this pattern. To debug i removed everything after the question mark (e.g. app.get('/data/:filename, routes.getdatabase);) and any filename works. Is there some module i need to require in order to use this query string syntax or is there anything else wrong with this get request?
Query strings are not a part of the route path.
Given your second example:
app.get('/data/:filename', routes.getdatabase);
You should be able to use req.query.get for your query param.
routes.js
exports.getdatabase = function(req, res, next) {
console.log(req.params.filename);
console.log(req.query.get);
// Do some stuff
return res.send(someResponse);
}
Console (URI: /data/someFile?get=cats):
someFile
cats

Nodejs Mysql connection pooling using mysql module

We are using mysql module for node and i was just wondering if this approach is good or does it have any bad effects on our application, consider this situation
dbPool.getConnection(function(err, db) {
if(err) return err;
db.query()
Here i am calling the dbPool object and requesting a connection from the pool then using it. However i found another implementation (which is the one i am asking about) which uses the dbPool object directly like:
dbPool.query('select * from test where id = 1' function(err, rows) {})
so i was wondering what does the second implementation does exactly, does it automatically return a free connection and use it ? can explain what is happening exactly in the second case and if it has any effect + or - on my application ? Thank you.
So this is so what called callback chaining. In NodeJS you have a lot of asynchronous calls going around. But sometimes you want to do something when the connection is done with MySQL. That's why the getConnection functionality has a callBack feature.
dbPool.getConnection(function(err, db) {
if(err) return err;
db.query()
Is equal to this:
dbPool.query('select * from test where id = 1' function(err, rows) {})
dbPool.query() will wait for the connection to be open, you don't have to put all your queries inside the getConnection to make it work. This is why it also has a callBack feature.
Tell me if I'm wrong. I hope this solves your question.