How to analyze JS Literals/Identifiers using ESLint Custom Rules - javascript

I'll explain the scenario with an example.
Suppose I have following JS code:
$.ajax({
url: '/Department/GetAllUsers',
type: "POST",
data: data,
success: function (result) {
//Some Code
},
error: function () {
//Some Code
}
});
And I want to restrict call to that action of the controller. So I have written following Custom ES Lint rule for this:
module.exports = {
meta: {
type: "problem",
docs: {
description: "Prohibited Method",
category: "Method",
recommended: true,
url: ""
},
messages: {
messageDefault: "This method is Prohibited to use"
},
fixable: "code",
schema: [] // no options
},
create: function (context) {
return {
Literal(node) {
var literalValue = node.value.toString();
var cont = literalValue.split("/").filter(x => x.length > 1);
{
if (cont[0] === 'Department' && cont[1] === 'GetAllUsers') {
context.report({
node: node,
messageId: "messageDefault",
});
}
}
}
};
}
};
So here I am restricting use of 'Department/GetAllUsers' which is working great. The problem arises when I split the string or assign the string to a variable. For example
var controller = "Department";
var action = "GetAllUsers";
$.ajax({
url: "/" + controller + "/" + action,
//or '/Department/' + 'GetAllUsers'
type: "POST",
data: data,
success: function (result) {
//Some Code
},
error: function () {
//Some Code
}
});
Here the restriction does not work, is there a way in which I can resolve the variable values at the url? Is this even possible using ESLint?
In short I want something like the context.SemanticModel.GetSymbolInfo(node) which is used in Roslyn for C# code analysis.
Thanks

You can use ESLint's scope manager
https://eslint.org/docs/developer-guide/scope-manager-interface
There are many examples of using the scope manager in ESLint's own codebase:
https://github.com/eslint/eslint/search?q=getScope
Using this API you can follow the variable reference and inspect its assignments.
Note that this has some limitations. For example you won't be able to track values across module boundaries or function boundaries.

Related

AngularJS - Correctly formatting asynchronous calls

newbie here.
I am trying to understand how I need to structure asynchronous calls within my controller to fit my specific use case:
Consider the following code snippet from an Angular Module in "service.js" within my project:
function getSearchObjects(projectName, title) {
var payload = JSON.stringify({
"title": title
});
var request = $http({
method: 'post',
url: URL + '/search/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
};
function runQuery(projectName, fromDate, toDate, sort, direction, columns) {
var from = Date.parse(fromDate);
var to = Date.parse(toDate);
var payload = JSON.stringify({
"fromDate": from,
"toDate": to,
"sort": sort,
"direction": direction,
"columns": columns
});
console.log(payload);
var request = $http({
method: 'post',
url: URL + '/query/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
}
function handleSuccess(response) {
return response.data;
};
function handleError(response) {
if (!angular.isObject( response.data ) || !response.data.error) {
return( $q.reject( "An unknown error occurred." ) );
}
return $q.reject( response.data.error );
};
});
Within my controller, I am trying to troubleshoot the following function:
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date, objectProperties.sort, objectProperties.direction, objectProperties.columns)
},
function(error) {
console.log(error);
});
};
getSearchObjects matches a title ($scope.selected.search) selected in my UI and grabs the following more detailed object from an API call:
{ title: 'Duplication Example',
sort: '#_traac-timestamp',
direction: 'desc',
columns: [ '#_traac-remote_ip', 'c-platform-m-distinct-id_s', '_type' ] }
I am trying to grab the properties returned from getSearchObjects and pass them along with a few user selected values from my UI to runQuery, which then returns data from a database to the user, but when I check the values passed to runQuery using the above logic in my controller, I get the following values. All of the objectProperties values I am attempting to pass to runQuery are undefined:
project_name: "Example Project"
start_date: 1499770800000
end_date: 1499943600000
sort: undefined
direction: undefined
columns: undefined
I have been trying to debug this, but I am too new to using Angular and asynchronous calls to really understand what I am doing wrong. My best guess currently is that I am calling runQuery before the values retrieved from getSearchObjects are attached to objectProperties. Either that or I am incorrectly referencing the properties within the objectProperties variable.
Could someone help me troubleshoot this issue, and better understand what I am doing wrong?
Thank you in advance for your help!
When you do this:
var objectProperties = some async function...
You are assigning the promise of the async function to the variable, not the result of it.
The result is coming in the .then, like you declared:
.then(function(result) { ... }
So, instead of objectProperties.sort, objectProperties.direction, objectProperties.columns, try using result.sort, result.direction, result.columns :)
If you are new to Promises, take a look at this simple, but great tutorial.
EDIT
Based on your comment, you are receiving, inside the response.data, the following object:
{"objectMatch": {
"title": "doc-event",
"sort": "#_traac-timestam‌​p",
"direction": "desc‌​",
"columns": [
"m-doc-‌​name_s",
"m-user_s",
"‌​m-full-action-type_s‌​",
"m-event-action-de‌​scriptor_s"
]}
}
So you have: response > data > objectMatch > properties you want.
The response.data you are extracting on your handleSuccess function:
function handleSuccess(response) {
return response.data;
};
So here, your result is response.data, containing the property objectMatch.
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
...
},
...
If all of that is correct, you should be able to access the values you want using result.objectMatch.<sort, direction or columns>, like:
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date,
result.objectMatch.sort, result.objectMatch.direction, result.objectMatch.columns)

How to use Trello JS API to create a card

I've been trying to utilize the Trello API via JSFiddle and haven't been able to get it to work (I have very limited JS/JSON knowledge). I need to create a card under a specific list, using the API.
function PostStuff()
{
$(document).ready(function(){
Trello.authorize({
interactive: true,
type: "popup",
expiration: "never",
name: "surveyrequest",
persist: "true",
success: function() { onAuthorizeSuccessful(); },
error: function() { onFailedAuthorization(); },
scope: { read: true, write: true}
});
function onAuthorizeSuccessful() {
Trello.post("cards", { name: "Card created for test", desc: "this is a test", idList: "........", due: null, urlSource: null});
}
});
}
I have JQuery and the Trello API included. I blanked out the idList in the code for security purposes. I confirmed that the code does execute the onAuthorizeSuccessful() function.
How can I modify this to create a Trello card?
function Auth() {
Trello.authorize({
type: 'popup',
name: 'your app name',
scope: {
read: true,
write: true },
expiration: '30days',
success: authenticationSuccess,
error: authenticationFailure
});
var authenticationSuccess = function(data){ /*your function stuff*/};
var authenticationFailure = function(data){ /*your function stuff*/};
}
this code works for me. i get function Auth() triggered on button click.
Also, you might have some issues with tokens which are expired, so Trello.deauthorize(); could be used on create new card failure function (it all depends on create new card error message).
regarding the create a new card...
var newCard =
{name: jQuery('input#tc_title').val(),
desc: jQuery('textarea#tc_desc').val(),
pos: "top",
idList: trello_list_id_var
};
Trello.post('/cards/', newCard, success, error);
var success = function(data){ /*..............*/}
var error= function(data){ /*..............*/}
in success/error functions you are able to check the error data
EDIT:
also i think that Trello.post("cards" ... should be replaced with Trello.post("/cards/" ... that might be the problem...

How to setup CURD with KendoUI grid for use with Kendo-Angular and an Angular OData factory?

In a previous project, where I was not using Angular, I setup a Kendo.DataSource that used an OData endpoint as follows:
var userDS = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: "/api/Users?$filter=USERGROUPS/any(usergroup: usergroup/ID eq '" + groupData.ID + "')", // only need to expand users for the selected group
dataType: "json", // the default result type is JSONP, but WebAPI does not support JSONP
},
update: {
url: function (data) {
// TODO: write UpdateEntity controller method
return "/api/Users(" + groupData.ID + ")";
},
dataType: "json"
},
destroy: {
url: function (data) {
// TODO: write Delete controller method
return "/api/Users(" + groupData.ID + ")";
},
dataType: "json"
},
parameterMap: function (options, type) {
// this is optional - if we need to remove any parameters (due to partial OData support in WebAPI
var parameterMap = kendo.data.transports.odata.parameterMap(options);
return parameterMap;
}
},
Now, introducing AngularJS into the mix, I would like to know how to define the read, update and destroy events using my AngularJS factory, where there is no URL.
My factory contracts are setup as follows:
contentTypesFactory.getList()
contentTypesFactory.insert(contentType)
contentTypesFacotry.remove(id)
The first problem I see with .getList() is that it doesn't take in any query string parameters, like $orderby and $inlinecount=allpages which I need for use with the KendoUI Grid. It is inside this factory that the URL is defined, then calls an abstract factory (see below).
I need to somehow pass in the URL and the entity name to my factory from the kendo.datasource url: function (remember, that the grid control will append whatever OData querystring parameters are required).
So, how I would setup the factory to output the data expected for each of the CRUD events.
Data source definition:
$scope.contentTypesDataSource = new kendo.data.HierarchicalDataSource({
type: "odata",
transport: {
read: {
//url: "/api/UserGroups?$orderby=GROUPNAME",
url: '/odata/ContentTypes',
//function (data) {
// pass in the URL to the abstract factory
//},
dataType: "json" // the default result type is JSONP, but WebAPI does not support JSONP
},
update: {
},
destroy: {
},
parameterMap: function (options, type) { ...
Abstract repository:
app.factory('abstractRepository', [function () {
// we will inject the $http service as repository service
// however we can later refactor this to use another service
function abstractRepository(repositoryService, whichEntity, odataUrlBase) {
//this.http = $http;
this.http = repositoryService;
this.whichEntity = whichEntity;
this.odataUrlBase = odataUrlBase;
this.route;
}
abstractRepository.prototype = {
getList: function () {
return this.http.get(this.odataUrlBase);
},
get: function (id) {
return this.http.get(this.odataUrlBase + '/' + id);
},
insert: function (entity) {
return this.http.post(this.odataUrlBase, entity);
},
update: function (entity) {
return this.http.put(this.odataUrlBase + '/' + entity.ID, this.whichEntity);
},
remove: function (id) {
return this.http.delete(this.odataUrlBase + '/' + id);
}
};
abstractRepository.extend = function (repository) {
repository.prototype = Object.create(abstractRepository.prototype);
repository.prototype.constructor = repository;
}
return abstractRepository;
}]);
ContentTypesFactory.js:
// each function returns a promise that can be wired up to callback functions by the caller
// the object returned from the factory is a singleton and can be reused by different controllers
app.factory('contentTypesRepository', ['$http', 'abstractRepository', function ($http, abstractRepository) {
var odataUrlBase = '/odata/ContentTypes'
var whichEntity = 'ContentTypes';
function contentTypesRepository() {
abstractRepository.call(this, $http, whichEntity, odataUrlBase);
}
abstractRepository.extend(contentTypesRepository);
return new contentTypesRepository();
}]);
After looking at kendo-examples-asp-net, I'm thinking that I should do away with the ContentTypesFactory and the abstract repository and call the OData endpoint directly - of course this is relatively easy.
However, my initial reason for creating an Angular repository was so that I could do JS unit testing on the data functions. To retain this feature, how can I call the abstract repository directly from the data source functions, and this the recommended way of accomplishing this?

Typeahead.js include dynamic variable in remote url

I have tried for hours now, to get a variable in my "remote" path. The variable will change, depending on another input. Here is the code:
school_value = $('#school').val();
$('#school').change(function () {
school_value = $(this).val();
$('#programme').typeahead('destroy'); // I have also tried with destroy - but it doesnt work.
});
$('#programme').typeahead({
remote: 'typeahead.php?programme&type=1&school_name=' + school_value,
cache: false,
limit: 10
});
The variable 'school_type' is not set in the remote addr, and therefore not called.
Do you have any clue how to get it working? I have just switched from Bootstrap 2.3 to 3, and then noticed typeahead was deprecated. Above code worked on Bootstrap 2.3, but it seems like when the script is initialized, the remote path is locked.
I have found the solution! Code:
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
replace: function () {
var q = 'typeahead.php?programme&type=1&school_name=';
if ($('#school').val()) {
q += encodeURIComponent($('#school').val());
}
return q;
}
},
cache: false,
limit: 10
});
Based on this threads answer: Bootstrap 3 typeahead.js - remote url attributes
See function "replace" in the typeahead.js docs
I believe the accepted answer is now out of date. The remote option no longer has replace. Instead you should use prepare:
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
prepare: function (query, settings) {
settings.url += encodeURIComponent($('#school').val());
return settings;
}
}
});
One issue I ran into was pulling the value from another typeahead object. Typeahead essentially duplicates your input, including all classes, so you have two nearly identical objects, one with the tt-hint class and the other with tt-input. I had to specify that it was the tt-input selector, otherwise the value I got was an empty string.
$('.field-make').val(); // was "" even though the field had a value
$('.field-make.tt-input').val(); // gave the correct value
Bloodhound remote options
There is actually a slight refinement of Mattias' answer available in the newer Bloodhound js, which reduces duplication and opportunity for error:
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
replace: function (url, query) {
if ($('#school').val()) {
url += encodeURIComponent($('#school').val());
}
return url;
}
},
cache: false,
limit: 10
});
#Mattias, Just as a heads up, you could clean up your replace method a little by supplying the optional url parameter.
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&type=1&school_name=',
replace: function (url, query) {
// This 'if' statement is only necessary if there's a chance that the input might not exist.
if ($('#school').val()) {
url += encodeURIComponent(('#school').val());
}
return url;
}
},
cache: false,
limit: 10
});
Am I looking at the same thing as all of you?
http://www.runningcoder.org/jquerytypeahead/
It looks like it has changed AGAIN! It is not very obvious how to do it in the documentation, but there is example code. I pulled this straight from the code in the documentation.
There is a second example in the documentation where they do it yet a different way! This way is the most succinct I think.
// Set a function that return a request object to have "dynamic" conditions
dynamic: true,
source: {
tag: {
ajax: function (query) {
if (query === "hey") {
query = "hi"
}
return {
url: "http://www.gamer-hub.com/tag/list.json",
dataType: "jsonp",
path: data,
data: {
q: query
}
}
}
}
}
And here is my working example:
source: {
ajax: function() {
var filter = {
partnerId: #Model.PartnerId,
productTypeId: #Model.ProductTypeId,
unitType: $("[name=UnitType]").val(),
manufacturer: "",
columnName: "#nameof(SaleViewModel.Manufacturer)"
};
var queryString = $.param(filter);
return {
url: recentEntriesBaseUrl + "?" + queryString
}
}
},
If you want to use wildcard parameter %QUERY, then add url = url.replace("%QUERY", q);
$('#programme').typeahead({
remote: {
url: 'typeahead.php?programme&q=%QUERY',
replace: function (url, q) {
url = url.replace("%QUERY", q);
let val = $('#school').val();
if(val) url += '&school_name=' + encodeURIComponent(val);
return url;
}
},
limit: 10
});

Backbone - Declare Default Parameters for a Fetch inside a Model

I have some global parameters that I want to be sent in every time I call a fetch on a collection... my issue is I don't want to declare the data: { ... } every time I fetch.
Is there a way I can provide default parameters inside the Collection itself with the possibility to add more or override some?
For example:
Instead of doing this every time:
this.articlesCollection.fetch({
dataType: 'jsonp',
data: {
deviceType: GlobalVars.deviceType,
memberId: GlobalVars.memberId,
authToken: GlobalVars.authToken,
targetObjectId: userId,
limit: 50,
excludeArticleBodies: true,
excludeViewedItems: false
},
success: function() {
_this.render();
}
});
I'd like to just provide a one or two parameters and a success function, like this:
this.articlesCollection.fetch({
data: {
targetObjectId: userId
},
success: function() {
_this.render();
}
});
... and have the Collection look something like:
define([
'underscore',
'backbone',
'global',
'utilities',
'models/article/ArticleModel'
], function(_, Backbone, GlobalVars, Utils, ArticleModel){
var ArticlesCollection = Backbone.Collection.extend({
model: ArticleModel,
initialize : function(view) {
this.view = view;
},
dataType: 'jsonp',
data: {
deviceType: GlobalVars.deviceType,
memberId: GlobalVars.memberId,
authToken: GlobalVars.authToken,
limit: 50,
excludeArticleBodies: true,
excludeViewedItems: false
},
url : function() {
return GlobalVars.baseAPIUrl + '/API/GetArticles';
},
parse : function(data) {
return data.Articles;
}
});
return ArticlesCollection;
});
Here's a working jsFiddle with one approach: http://jsfiddle.net/LEuGq/1/
Basically, you configure both an object of defaultParams and params as properties of your collection, which are used to dynamically compute the correct URL when fetch() is called. This way is probably more in alignment with backbone than changing the API of fetch() to accept parameters, which it is not designed to do.
var ParamCollection = Backbone.Collection.extend({
defaultParams: {deviceType: 'raceCar', limit: 42},
params: {},
url: function() {
return "/paramcollection?" + $.param(_.defaults(this.params, this.defaultParams));
}
});
var paramCollection = new ParamCollection();
paramCollection.params.excludeArticleBodies = true;
paramCollection.params.limit = 52;
$("#debug").append(paramCollection.url());
Backbone uses jQuery's ajax call by default, so you can set up anything you need as a default using various methods. See this question for some examples: jQuery's ajaxSetup - I would like to add default data for GET requests only

Categories