How to JOIN two SQL tables from the front end/ what REST api would i use - sql

This probably is a two part question. So What I'm wanting to do is have to tables JOIN by their ID's but when I want that join to happen would be with a function from the front end (IE a button click or something similar). But what I'm wondering is what is the REST command I would use for wanting to do something like this? I'm thinking GET? and also if it is how would I pass two Id's to the back end with the request? I understand how to do one parameter with:
this.testName = function(id) {
return $http({
method: 'GET',
url: '/api/order/:id'
}).then(function(response) {
console.log(response);
return response.data
});
};
I would think it would be as simple as passing in a second parameter , but I'm not sure what I need to make my url in node to pass in two separate id's.
Any and all help appreciated, if I'm overthinking this please slap some sense into me!

You are thinking correctly. Create and endpoint to return what you want based on your request.
To pass two ids try something like this:
url: '/api/order/:orderId/otherId/:otherId'

Related

How to attach multiple parameters to an API request?

I built my own simple REST API with Express and now I'm consuming it from my client (Vue.js)
So in my page I access all the data from this endpoint: GET /api/books, and it works fine
Now I also have a "sort by" button where I want to get the data by the latest entries. I don't know if that's a good way or if I have to handle this in the backend but what I do is calling the same endpoint which is GET /api/books and sorting the data to get them the right way
For ex:
sortByLatest() {
axios
.get("/api/books")
.then(res => {
const books = res.data;
const sortedBooks = books.sort((a, b) => b.createdAt > a.createdAt ? 1 : -1
);
this.books = sortedBooks;
})
// catch block
}
I do that for everything. If I need a limited number of results or a specific property from the data I have to write some logic in the axios .then block to sort or filter what I want. Is this bad practice?
But that's not my actual problem
My problem is, in addition of sorting by the latest entries, I also want to filter the results by a specific property. The problem is when I click the A button it's gonna filter the books by a specific property, and when I click the B button it's gonna sort them buy the latest entries, but not both at the same time!
And what if I want additionnal things like limit the number of results to 10, filter by other properties etc... I want to be able to create requests that ask all those things at once. How can I do that? Do I have to build that in the backend?
I saw some websites using url parameters to filter stuff, like /genre=horror&sort=latest, is that the key of doing it?
Thank you for your time

Use filtered list in datatables to send multiple emails

I'd like to be able to send emails based on a search completed in Datatables. I use a json array created from a mysql db and serverside datatables.js processing to create the table. The table creates a filtered list (Showing 1 to 35 of 35 entries (filtered from 60 total entries)), and I'd like to be able to send an email to those 35 people. I'm very new to ajax and javascript, but have some experience in php. Is this possible?
It's absolutely possible.
You may need to extract your visible rows data:
var selectedRows = datatable.rows({filter:'applied'}).data()
Pass that data via $.ajax() call to your backend php-script and perform necessary 'e-mail' job server side.
Without your code and knowing exact environment, I believe, that's the best I could say.
I tried:
$('#export').click(function () {
$.ajax({
url : 'emget.php',
type : 'post',
data : table.column(4,{search:'applied'}).data().toArray(),
dataType: 'json',
success : function(returnedData) {
console.log(returnedData);
}
});
});
When I view the output, it seems to put out the correct number of records, but it says "Undefined" for each record it seems to try to export. Column 4 has the email addresses that I would need to pass to PHP.

How do I implement, for instance, "group membership" many-to-many in Parse.com REST Cloud Code?

A user can create groups
A group had to have created by a user
A user can belong to multiple groups
A group can have multiple users
I have something like the following:
Parse.Cloud.afterSave('Group', function(request) {
var creator = request.user;
var group = request.object;
var wasGroupCreated = group.existed;
if(wasGroupCreated) {
var hasCreatedRelation = creator.relation('hasCreated');
hasCreatedRelation.add(group);
var isAMemberOfRelation = creator.relation('isMemberOf');
isAMemberOfRelation.add(group);
creator.save();
}
});
Now when I GET user/me with include=isMemberOf,hasCreated, it returns me the user object but with the following:
hasCreated: {
__type: "Relation"
className: "Group"
},
isMemberOf: {
__type: "Relation"
className: "Group"
}
I'd like to have the group objects included in say, 'hasCreated' and 'isMemberOf' arrays. How do I pull that using the REST API?
More in general though, am I approaching this the right way? Thoughts? Help is much appreciated!
First off, existed is a function that returns true or false (in your case the wasGroupCreated variable is always going to be a reference to the function and will tis always evaluate to true). It probably isn't going to return what you expect anyway if you were using it correctly.
I think what you want is the isNew() function, though I would test if this works in the Parse.Cloud.afterSave() method as I haven't tried it there.
As for the second part of your question, you seem to want to use your Relations like Arrays. If you used an array instead (and the size was small enough), then you could just include the Group objects in the query (add include parameter set to isMemberOf for example in your REST query).
If you do want to stick to Relations, realise that you'll need to read up more in the documentation. In particular you'll need to query the Group object using a where expression that has a $relatedTo pointer for the user. To query in this manner, you will probably need a members property on the Group that is a relation to Users.
Something like this in your REST query might work (replace the objectId with the right User of course):
where={"$relatedTo":{"object":{"__type":"Pointer","className":"_User","objectId":"8TOXdXf3tz"},"key":"members"}}

Right way to dynamically update view in Angular

What is the right way to updated the Model in the view, say after a successful API POST. I've a textarea, something like in a Twitter, where a user can enter text and post. The entered text must show up soon after it is posted successfully.
How to achieve this? Should I make another call to get the posts separately or is there any other way to do this?
My Code looks like
feedsResolve.getFeeds().then(function(feeds){
$scope.feeds = feeds;
}
where feedsResolve is a service returning a promise
$scope.postFeed = function(){
var postObj = Restangular.all('posts');
postObj.post( $scope.feed.text ).then(function(res){
//res contains only the new feed id
})
}
How do I update the $scope.feeds in the view?
I assume you are posting a new post and that generally posts look like:
{
id: 42,
text: 'This is my text'
}
In this case you can do something like:
$scope.postFeed = function(){
var postObj = Restangular.all('posts');
var feedText = $scope.feed.text;
postObj.post( feedText ).then(function(res){
$scope.feeds.push({ id: res.id, text: feedText});
})
};
A better practice when writing restful service though is to just have your POST return an actual JSON object with the new feed that was added (not just the id). If that were the case you could just add it to your feeds array.
If your JSON object is complex, this practice is the most common an easiest way to handle this without needing extra requests to the server. Since you already are on the server, and you've likely already created the object (in order to be able to insert it into the database), all you have to do is serialize it back out to the HTTP response. This adds little to no overhead and gives the client all the information it needs to effortlessly update.

How to define complex routes with named parameters in express.js?

I want to set up some more complex routes that can include a number of optional parameters. Preferably, I would like to use named parameters for ease of access. Here is an example of what I'm trying to achieve:
// The following routes should be matched based on parameters provided:
// GET /books/:category/:author
// GET /books/:category/:author/limit/:limit
// GET /books/:category/:author/skip/:skip
// GET /books/:category/:author/limit/:limit/skip/:skip
// GET /books/:category/:author/sort/:sortby
// GET /books/:category/:author/sort/:sortby/limit/:limit
// GET /books/:category/:author/sort/:sortby/skip/:skip
// GET /books/:category/:author/sort/:sortby/limit/:limit/skip/:skip
app.get('/books/:category/:author/(sort/:sortby)?/(limit/:limit)?/(skip/:skip)?', myController.index);
As you can see, I'm trying to group the optional parameters with (paramKey/paramValue)?. That way I was hoping to be able to "mix and match" the optional parameters while still making use of the parameter naming. Unfortunately, this doesn't seem to work.
Is there any way to get this working without having to write straight regular expressions and adding additional logic to parse any resulting index-based parameter groups?
Basically, I'm looking for an easy way to parse key/value pairs from the route.
It looks like you want to re-implement the query string using the URL path. My guess is that if you really wanted that, yes, you would have to write your own parsing/interpreting logic. AFAIK express path parameters are positional, whereas the query string is not. Just use a query string and express will parse it for you automatically.
/books?category=sports&author=jack&limit=15?sortby=title
That will enable you to do
req.query.sortby
You may be able to get express to do 1/2 of the parsing for you with a regular expression path like (:key/:value)* or something along those lines (that will match multiple key/value pairs), but express isn't going to then further parse those results for you.
you can send data to view as follow:
//in the server side ...
app.get('/search/:qkey/:qvalue', function(req, res){
res.write(JSON.stringify({
qkey:req.params.qkey;
qvalue:req.params.qvalue;
}));
});
and in the client side... call to ajax
$.ajax({
type:"POST",
url:"/search/"+qkey+"/"+qvalue,
success: function(data){
var string = eval("(" + data + ")");
//you access to server response with
console.log(string.qkey+" and "+ string.qvalue);
}
});