What is the REST style for getSomethingByAnother() method - javascript

I have a Node.js REST API service and I have a resouce - Link for example.
To get all links I use GET /links
To submit new link I use POST /links
To get one link by linkid I use GET /links:id
Each link have an array of Tags and I need a REST style URI to get the links by tag value. What will be REST style URI in this case ?

For getting the links of a certain tag you can define the following route:
/tags/:tagID/links
And for getting tags of a certain link:
/links/:linkID/tags

I think it should be:
GET /links/:id/tags
that should return all the tags related to the link with id ":id"
If you like to work with your tags as a separated thing you could do it like this:
GET /tags ==> retrieve all tags.
GET /tags/:id ==> retrieve tag with id..
GET /tags/links/:id
Also resftull is not strict, and some times, the resource, or action that you need to execute does not fit in that schema, and you can create a custom method:
GET /tags/get-for-link-id/:id => retrieve tags related to a link
That example is pointless, but consider that you are having a complicated route with so much params eg:
GET /tags?q=return&state=active&sort=date if this request is repeated so much times, for your api customer it would be pleasant to have a custom alias like GET /tags/activeByDate

It depends. TYou can do something like /blah:{tagId}/ (which is perfectly valid URI as well). Or you can do /links/?tagID={id} and so on. I don't prefer the already mentioned hierarchical URI /tags/{id}/links, I think a flat URI is much better. If the relationship has attributes as well, then you can use /tag-link-relationships/{relationshipId} or /tag-link-relationships/tag:{tagId}/ or /tag-link-relationships/?tag={tagId} etc...
From client perspective the URI structure does not matter, because the client follows the hyperlinks the service responds with (aka. uniform interface / HATEOAS constraint).
off: Almost every day we got this question, at least try to search next time.

Related

How to prevent tracking sensitive data in URLs?

Some URLs in my single-page-app (SPA) contain sensitive information like an access token, user information, etc.
Examples:
/callback#access_token=HBVYTU2Rugv3gUbvgIUY
/?email=username#example.com
I see that hotjar allows suppressing DOM elements and images from tracked data. Is it possible to hide params in URL or at least disable tracking for some pages?
Since you are saying that it is your SPA, you might solve the problem by switching from GET requests (which have the parameters inside the URL) to POST requests. I do not know hotjar, but if you tell the tracking service to analyze URLs only, that would be an option worth considering.
Another option frequently used is to obfuscate your parameters in the URL, see e.g. Best way to obfuscate an e-mail address on a website? However, that is never a really safe solution for sensitive data, since the de-ciphering step is too easy, in particular if your man-in-the-middle has all requests ever send to your SPA.
Edit. I just found in the Hotjar allows RegEx. Assuming you could enter a regular expression of URL-parts to exclude.
The general syntax /foo/bar/ means that foo should be replaced by bar, in our case, we want to delete the given snippet, that why it is /foo//.
For the given case of the access token, the regular expression would be
/callback#access_token=[a-zA-Z0-9]{15}//
and respectively for the email part of the URL
/\?email=(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])//
This second RegEx partially taken from How to validate an email address using a regular expression?
It seems to me that it's reasonable to assume that tracking scripts will try to access window.location.href or similar to get the current url which they will store.
So a possible solution would be create a dynamic scope which has a different value for window.location.href (with all sensitive info filtered out)
This is how it might work:
// get the tracker script as a string, so you can eval it in a dynamic scope
let trackerScript = 'console.log("Tracked url:", window.location.href)';
// now lets lock it up
function trackerJail(){
let window = {
location: {
// put your filtered url here
href: "not so fast mr.bond"
}
}
eval(String(trackerScript))
}
trackerJail()
If the tracking snippet is wrapped in a function it might be possible to create a dynamic scope for it without running eval by overriding it's prototype instead. But I'm not sure you can count on tracker scripts being wrapped in a neat function you can modify.
Also, there are a couple more ways the script might try to access the URL, so make sure to cover all the exits
If you control the page and order of scripts, you could read the data from the url then delete it before anything else can get to it.
proofOfConcept.html
<script id="firstThingToLoad.js">
console.log(window.location.href);
const keyRegex = /key=[^&]*/;
const key = window.location.href.match(keyRegex);
console.log("I have key", key);
const href = window.location.href.replace(keyRegex, "");
history.replaceState({}, "", href);
</script>
<script id="someSnoopyCode.js">
console.log("I'm snooping: ", window.location.href);
</script>
<body>
Link to private
</body>
Of course the Link to private should not exist as is. Also, this does break refresh and most navigation in general, though there are ways to catch and save that.

How to display an HTML Element from an external site

Let's say I know a class id, is it possible to read the HTML data and write as a string the HTML that contacts that class id?
Doesn't have to be concrete code for this, any resources are appreciated that may make this possible. I'm unsure if there are any javascript functions that allow this.
If you are accessing this from another site and assuming you have CORS setup to allow the request, you can use jQuery's get() to fetch the item:
$.get('https://example.com/path/to/page.html')
.then(function(data){
var elem = $(data).find('yourSelector');
/*
Do something with the element
*/
});
This also assuming that the element is always on the page and the page always resolves.

Google Tag Manager Virtual Page View

I have a little problem setting up a virtualPageView which should override the URL which is sent to google when no result is present.
Heres what I have as JavaScript code:
function returnNoSearchResultsGoogleTagManagerCode($searchterm){
if ($searchterm == "") return "";
$requestUri = $_SERVER['REQUEST_URI'] . "&no_result=".$searchterm;
$js = "<script>
$(document).ready(function(){
dataLayer.push({
'event':'empty_result',
'virtualPageURL':'".$requestUri."'
});
});
</script>";
return $js;
}
As you can see, I want to use an event trigger (empty_result).
In google, I use a Trigger to determine if the Page is a no result Page. First i created a custom Variable with custom JS
function(){
if (document.getElementsByClassName('ga-no-result').length > 0){
return true;
}else{
return false
}
}
The class is set, if the SearchEngine can't find a result. So far so good.
I also created a dataLayer variable to hold the virtualPageURL
Now I need an event which is triggered if the variable is true.
Finally I created a Tag with type PageView which is fired when the event occurs:
Until now it seems okay, the Tag is properly configured (i guess) but if I do a search which has no result, the Page URL is not overridden
The Tag is properly fired and the variables are filled. The overview of the dataLayer shows a correct dataLayer event.
But the PageURL is not overridden... Even if I wait a whole day, the category isn't sent to google.
What am I doing wrong?
I would be very thankful if someone would have an idea or even a solution :)
Thanks in advance
exa.byte
UPDATE:
Hey, I forgot to mention, that I want to use the new page variable as the string which google should use to determine the searchterm and the searchcategory
In Google Analytics I configuered the search as the "q" parameter and the "no_result" as the category.
Is it even possible to change the string which google will parse in the end?
To send a virtual pageview to Google Analytics, the field you need to change is page not {{Page Url}} , also the title field is often used.
That's really the only two things you need to do to send a simple virtual pageview.
Extra: I always start my pagepath with /virtual/ to be able to recognize which ones are virtual pageviews easily in GA
For virtual page view you have to change Field "page" - in your GTM-OnSearchEmptyResult you are changing "{{Page URL}}" - I don't think that's correct way to send virutal pageview. Also if you need to change hostname use Fieldname "hostname".
In preview mode you will not see Page URL changed in Variables Tab, you have to go to the actual GA tag that is fired and check it's values. You can either do this in GTM's preview tool or you can use standard developer tools - Network Tab and see what values are being sent to GA:
You can see "dl" parameter is the current page, if you set up virtual page you should also see parameter called "dp" this is going to be the new value of page in your GA.
If you want to setup virtual pageview you have to use page instead of {{Page URL}} in your fieldname and for Document title use title in you fieldname.
for more field reference of google analytics follow below link
https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#hitType.
If you don't want to mess around with custom Tag Manager events it's still possible to use the good old ga method, even if you don't include the Analytics code on the page. You just need to fetch the right tracker dynamically, as explained by Simo Ahava in this thread.
if (typeof ga === "function") {
ga.getAll().forEach((tracker) => {
tracker.set('page', '/my/path'); // <- change here
tracker.send('pageview');
});
}
I also put it in a gist here.
thanks for your help. I think I got rid of the Problem and have solved it now. I will describe my solution below:
The solution is quite simple.
I had an error/ spelling error # google backend. I set the search_category parameter to "no_results", but used "no_result" for implementation...
Pretty dumb, but sometimes you just won't see the wood for the trees...
I created a new Trigger as helper "HelperDomReady" to trigger the only if DOM is ready and the variable "isEmptySearch" equals "(bool)true"
Now I can see the searchterms which have no result in google backend in the "sitesearch categories" summary. Since I won't set the parameter at all, if the search had at least one hit, the site-search category shows "not-set" for successful results. Therfore the category-section will only show searches without a hit. Problem solved :)
Disadvantage: The searchterm is also listed in the normal list. But I think this is negligible

Replace URL in Angular environment

I need to modify the URL after opening a new window and navigating to a state.
My starting page looks like this:
localhost:8000/startpage.html.
When it loads the URL becomes
localhost:8000/startpage.html#/.
In the new window I am navigating to a new state:
localhost:8000/startpage.html#/newstate.
What I want is to have the URL looking like this:
localhost:8000/startpage.html?project=1#/newstate.
I am getting almost correct results except that instead of replacing the URL completely it adds
?project=1#/newstate to localhost:8000/startpage.html#/.
So the result is something like this:
localhost:8000/startpage.html#/%3Fproject=903%23/newstate
while what I need is:
localhost:8000/startpage.html?project=903#/newstate
Here is some relevant code:
if ($window.history.replaceState) {
var newUrl = '?project=903' + '#/case';
$location.path(newUrl);
$location.replace();
};
Seems to me I am having two problems. Extra '#/' after '.html' and the URL is encoded. Because even if I remove extra '#/' it still does not work unless I replace encoded characters with real ones.
Please help.
Thanks
I think you are using the wrong method. You want to be using $location.url which will allow you to set the path, query, and hash values all at once. But you may be better off setting the query and hash separately because you don't need to change the entire url.
$location.search('project', '903');
$location.hash('case');
I removed the / from the hash because it isn't necessary.
Also, by default angular uses hash mode to navigate its routes. If you want to supply a hash I think you will need to turn that behavior off.
$locationProvider.html5Mode(true);
Set that in your application's configuration.
Here is a good article: https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag
With AngularJs 1 the # sign usually follows the page that loads the ngApp Directive... pls correct me if i am wrong.
So i think the only solution to that is to have ngApp directive on the page link where you want the # tag appear...
It is a very bad practice tho.

Send variable value from page to another page

In my case :
I have created a form and in the form there is a button and a combo box that contains the data (Say it page A). When I click on the button, all I wanted was to call page B to perform a second process. The syntax for calling the page B is :
bb.pushScreen('PageB.htm', 'PageB', {'Key': MyComboValue});
How do I after page after page B called B will capture and get the value of the "MyComboValue" being sent from page A ??
Regards,
Bertho
Firstly, this is available in bbUI 0.94 (next branch) just to make sure you're running the right build.
Now, the object you pass to the new page is available in the ondomready, and onscreenready functions, so you would do something like this:
onscreenready: function(element, id, passed_object) { }
There are several ways to achieve this:
Use cookies to save the data. Wouldn't recommend it much.
Use localStorage. Works for newer browsers, some browsers won't be able to enjoy it.
Pass the values as querystring parameters when doing the change of url.
I would go with the third option myself. If you're only using JavaScript and you're not using any server side programming language:
Attach an event to the button so that when clicked, it fetches the data and generates a querystring. Then: top.location = "http://something/PageB.htm?" + querystring;
On the Page B, read the querystring (top.location.href) and parse it to get the querystring. Use the values of the querystring to set whatever you want on your page.
If you require code or if I misunderstood, please tell and I will check right away!
EDIT: I just realized you tagged your question as using blackberry-webworks. I have never worked with it and thus I have no idea if my solutions make sense on it. Try to specify it on your question too if possible, or in the title :)

Categories

Resources