Express + node.js API filtering - javascript

I am developing a node API.
I have endpoint like GET /messages
This wll return all messages. I want to have pagination on this endpoint something like
GET /messages?filter=my_filter_string&limit=10&offset=10
The filter statement will be like this
{fieldName1}={fieldValue1}&...{fieldNameN}>{fieldValueN}.
Operations can be =, > or <. < and > operations are only for number, integers and dates
I using sequelize as the ORM and postgresql as DB.
My question is how can I parse the my_filter_statement and convert it into a search criteria object for sequelize.
Also if I call the API like
GET /messages?filter="id=10&contentlength>20"&limit=10&offset=10
It is not working

Can you have, for example:
GET /messages?greater=1&less=5&limit=10&offset=10
And then in node:
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
And match the query parameters, such as greater/less than (which could be shortened to "gt" and "lt"), to the symbols you need in your statement?

Related

Handling SQL comparison operators in express GET routes - Filtering

I'm having struggle to use SQL comparison operators in express GET routes.
I know that, with MongoDB (using Mongoose), we can GET a route like so :
app.get('/users?age[gte]=20', …)
Which we can then handle like so in our controller function :
// Get the query parameters from the GET URL :
const queryObj = { ...req.query };
let queryStr = JSON.stringify(queryObj);
// Modify the comparison operators passed in the query (add the $ sign) :
queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, match => `$${match}`);
console.log(JSON.parse(queryStr)); // Returns { age: { '$gte': '20' } }
// With the above example - GET /users?age[gte]=20 -, we can then use it directly to fetch users with age >= 20 :
const users = await Users.find(JSON.parse(queryStr));
However, how can I do this for SQL comparison operators, using Knex ? As we don't want them to be nested in the query string object.
I tried different REGEX to get >=, >, <, <=, instead of the Mongoose ones ($gte, $gt,…), the problem is that, with the brackets in the query string, I get something like this :
queryStr = queryStr.replace(/\bgte\b/g, '>=');
console.log(JSON.parse(queryStr)); // Returns { age: { '>=': '20' } }
Because I use Knex, as far as I know, I can not directly use this kind of object in the query, as I did with Mongoose.
What is the best way to deal with this and "automate" the filtering function like I did with the Mongoose example ?
Thank you very much

how to fetch all values in single variable using java script

i am retrieving the all values in a for loop but i want to insert those values in database using single variable.It possible to store all values to the single record.
var emailId;
//log.info("testing 1234 = "+tw.local.EntityProMasterList.listAllSelected);
for (var i = 0; i < tw.local.EntityProMasterList.listAllSelected.listLength; i++){
emailId = tw.local.EntityProMasterList.listAllSelected[i];
log.info("testing 1 = "+emailId.value);
}
log.info("testing 1 = "+emailId.value);
You can user JSON.stringify() and save it as string:
var holder = {};
holder.var1 = "var1";
holder.var2 = "var2";
log.info("holder:"+JSON.stringify(holder));
The output will be:
holder:{"var1":"var1","var2":"var2"}
I believe your question is - given a list of values, how can I insert those values into the database as separate entries. If this is correct there is a right way and a wrong way to do this.
The wrong way is to simply put all the SQL into a string and use one of the DB services in the system data toolkit to execute. Something like -
insert into table blah values(1, 2, 3, 4);
This would be wrong because you are open to SQL injection attacks. There is a different service for parameterized queries. This takes 1 or more SQL statements and a list of parameters to use in them. The details are documented in the service so I won't repeat them here. Basically you would modify your query to have the ? Character where you need the data from your array. You then create arrays of parameters that fill out the values on execution.

How can match an object to a query with Javascript/AngularJS?

I am trying to find a way to return the URL of a query based on whether or not the data given was found within that query output. This is what I am doing and what I am trying to do:
var homes = ["home1","home2","home3"]; // Given
var addresses = [query1,query2]; //Given only as URLs
for(var i = 0; i < homes.length; i++){
/*Find the matching query to JSON object where home object is stored*/
var theRightAddress = find(homes[i],addresses);
/*Make sure the variable is found*/
console.log(theRightAddress);
}
In the data in query1 and query2 should appear as objects like:
[home1, home7, home32] /* for query1 */
[home2, home3, home102] /* for query2 */
BUT, I am only given the urls to these queries. So, Query1 may appear something like the link https://foo/foo/foo/query1 and Query2 like https://foo/foo/foo/query2.
So, addresses is actually:
var addresses = ["https://foo/foo/foo/query1","https://foo/foo/foo/query1"];
I am simply trying to match the addresses with the homes (that are given). I have tried AngularJS HTTP GET requests, but I can't seem to return any of the results since you need to use promises. All I am really looking for is a way to implement find() such that it returns the correct URL and sets theRightAddress.
Ex.) find("home1",addresses) should return:
https://foo/foo/foo/query1
Ex.) find("home2",addresses) should return:
https://foo/foo/foo/query2
Ex.) find("home3",addresses) should return:
https://foo/foo/foo/query2

Get specific object from Parse (.com) query result by field without going back to DB

So say I do a query on Parse database and get a results object, with each result having a field place_id.
How can I then get a specific object by place_id from the results without actually going back to the database (want to minimise network traffic and db querying...)?
This is what my query will look like:
var LatestUpdate = Parse.Object.extend("LatestUpdate");
var query = new Parse.Query(LatestUpdate);
query.containedIn("place_id", arrayOfplaceIds);
query.find().then(
function(results){
// and then i want to do something like:
return results.findByField("place_id", 1234) // get a specific object from the result without going back to the database?
}
);
You have to loop through your results and find the object that matches your criteria. You can do this easily using underscore.js which is supported on the cloud:
var match = _.find(results, function(object){ return object.get("place_id") == 1234; });
Just make sure your have var _ = require('underscore'); on top of your js file.

use express.js to get the query string of a url

I'm looking for a way to get the query string part of a url using node.js or one of it's extension module.
I've tried using url and express but they give me an array of parameters.
I want to original string.
Any ideas ?
example; for:
http://www.mydom.com?a=337&b=33
give me
a=337&b=33
(with or without the ?)
Use url.parse. By default it will return an object whose query property is the query string. (You can pass true as the second argument if you want query to be an object instead, but since you want a string the default is what you want.)
var url = require('url');
var urlToParse = 'http://www.mydom.com/?a=337&b=33';
var urlObj = url.parse(urlToParse);
console.log(urlObj.query);
// => a=337&b=33
How about using the built-in url.parse method?

Categories

Resources