Filter data obtained through GitHub API - javascript

I created this function to obtain GitHub issues:
retrieveEnerpriseIssues: function(repoOrg, repoName, callback) {
let data = null;
// token auth
octokit.authenticate({
type: 'basic',
username: config.githubEnterprise.username,
password: config.githubEnterprise.token
});
async function paginate(method) {
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue",
per_page: 100
});
data = response.data.items;
var count = 0;
while (octokit.hasNextPage(response)) {
count++;
console.log(`request n°${count}`);
response = await octokit.getNextPage(response);
data = data.concat(response.data.items);
}
return data;
}
paginate(octokit.search.issues)
.then(data => {
callback(data);
})
.catch(error => {
console.log(error);
});
}
It is called in this function which takes the issues, filters out all of the unwanted keys into json format and puts it in my db.
extractToDb: function() {
let gitIssues = null;
for(var i = 0; i < config.githubEnterprise.orgs.length; i++) {
for(var j = 0; j < config.githubEnterprise.orgs[i].repos.length; j++) {
gitHubService.retrieveEnerpriseIssues(
config.githubEnterprise.orgs[i].owner,
config.githubEnterprise.orgs[i].repos[j].repoName,
function(data, err) {
if(err) {
console.log('err: ', err);
} else {
gitIssues = data;
}
gitIssues = JSON.stringify(gitIssues);
gitIssues = JSON.parse(gitIssues);
let issueFormatForDb = null;
for(var i = 0; i < gitIssues.length; i++) {
issueFormatForDb = gitIssues[i];
const body = '{' +
'"github_id": "' + issueFormatForDb.id + '",' +
'"issue_title": "' + issueFormatForDb.title + '",' +
'"issue_number": "' + issueFormatForDb.number + '",' +
'"issue_url": "' + issueFormatForDb.url + '",' +
'"issue_state": "' + issueFormatForDb.state + '"' +
'}';
console.log('Body: ', body);
getGitHubIssues.postToDb(body);
}
});
}
}
}
I'd like to take this a step further by filtering out any issues where the state is closed. How is this done and should it be handled in my retrieveEnerpriseIssues function or my extractToDb?
Possible solution
I tried this in my extractToDb function:
gitIssues = JSON.parse(gitIssues);
gitIssues = _.where(gitIssues, {state: "open"});
let issueFormatForDb = null;
Is it the best solution or is there a better way?

As #givehug stated:
Better use _.filter, or native filter method like
gitIssues = gitIssues.filter(i => i.state === 'open')
I think .where was deprecated in later versions of lodash github.com/lodash/lodash/wiki/Deprecations. Other than that its perfectly fine.
I just realsied I can filter the state in my paginate function with this:
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue" + " label:issue_label" + " state:open",
per_page: 100
});

Related

Repetitive data when you load a combobox

I'm calling EventListener so that when something is typed into the username field, it will list that user's companies for me.
var ent = document.getElementById("username");
ent.addEventListener('change', async () => {
localStorage.clear();
self.empUsuario = new Array();
self.rucEmp = new Array();
var newUser = document.getElementById("username");
$('#empresa').empty();
await fetch(environment.apiPoint + '/empresas?usuario=' + newUser.value, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(datos => {
datos.forEach(e => {
self.todasEmpresasUsuario.push({
ruc: e.ruc,
nombEmp: e.nombreCorto
});
});
})
await self.todasEmpresasUsuario().forEach(
function (element) {
self.empUsuario.push(element.nombEmp);
self.rucEmp.push(element.ruc);
}
);
Then I give it a conditional if the user is different from null, that it shows me with the rucEmp, and if not an empty space.
var str = "";
var item = "";
if (newUser.value != '') {
self.cont = 0;
let vacio = '';
for (item of self.empUsuario) {
vacio = "<option value=''>" + ' ' + "</option>"
str += "<option value='" + self.rucEmp[self.cont] + "'>" + item + "</option>"
self.cont++;
}
if (newUser.value == '') {
//str += "";
str += "<option value='" + self.rucEmp[self.cont] + "'>" + item + "</option>"
$('#empresa').empty().append(str);
}
$('#empresa').empty().append(vacio + str);
}
I expected the company lists to appear for each user and not accumulate, but the lists accumulate in the select.

Unable to send dynamic invoice value to struts2 server

I am working on angularjs 1.6.5
I am using following code to send data of invoice page.
$scope.products = [{qty: 0, description: ' ', sellingPrice: 0.0, unitPrice: 0.0, total: 0.0}];
$scope.fproducts = [];
$scope.generateInvoice = function () {
console.log("generateInvoice");
console.log($scope.fproducts);
console.log("sub total " + $scope.subTotal + " ft " + $scope.finalTotal + " pamt " + $scope.paidAmount + " baldue " + $scope.balancedue);
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $filter('date')($scope.invoiceDate, "MM/dd/yyyy"),
};
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}
//commenting above for each and removing comment from below code is
// working properly but I want to send dynamic data with above code
/* $scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;*/
$scope.bd1[`BillPaidDetailses[0].paymentMode`] = $scope.paymentMode;
$scope.bd1[`BillPaidDetailses[0].amount`] = $scope.paidAmount;
console.log($scope.bd1);
$http({
method: 'POST',
url: 'added-invoice',
data: $httpParamSerializerJQLike($scope.bd1),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(data, status, headers, config) {
if (data.data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(data, status, header, config) {
$scope.success = false;
$scope.failure = true;
});
}
Above code is not passing value to server side object.
its console.log value is
on modifying above data
/*if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}*/
$scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;
as this is passing value to server object
its console.log is
I want to run my code using dynamic value specified in if condition.
What is the problem I am unable to get it.
EDIT I am using server side struts2
my code is
public class BillNewAction extends ActionSupport implements ModelDriven<BillDetails> {
BillDetails bd = new BillDetails();
private List<BillDetails> billList = new ArrayList<BillDetails>();
public String insert() {
System.out.println("total " + bd.getTotal()
+ " subTotal " + bd.getSubTotal() + " paid "
+ bd.getTotalPaid()
+ " invoiceDate " + bd.getInvDateStr()
);
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
try {
bd.setInvoiceDate((new java.sql.Date(formatter1.parse(bd.getInvDateStr()).getTime())));
} catch (ParseException ex) {
Logger.getLogger(BillNewAction.class.getName()).log(Level.SEVERE, null, ex);
}
for (BillPaidDetails b : bd.getBillPaidDetailses()) {
System.out.println("type " + b.getPaymentMode() + " amount "
+ b.getAmount()
);
}
System.out.println("product size " + bd.getBillPrList().size());
for (BillProduct b : bd.getBillPrList()) {
System.out.println("id " + b.getId() + " desc "
+ b.getDescription() + " qty " + b.getQty()
+ " sp " + b.getSellingPrice() + " up "
+ b.getUnitPrice() + " " + b.getTotal()
);
}
}
}
public class BillDetails implements java.io.Serializable {
private Long billNo;
private Client client;
private BigDecimal subTotal;
private BigDecimal TotalAmount;//total price
private BigDecimal TotalPaid;//Amount paid for getting items
private BigDecimal vat;
private BigDecimal total;
private String invoiceNo;
private Date invoiceDate;
private String invDateStr;
private List<BillPaidDetails> BillPaidDetailses = new ArrayList<BillPaidDetails>();
private List<BillProduct> billPrList = new ArrayList<BillProduct>();
//getter and setter
}
I have to send data in $scope.bd1[billProductList[0].id] = 1; format to server
Assigning indivisual value passing the data to server but I have dynamic no of values so I am trying
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[billProductList[${index}].${key}] = value;
});
});
}
that is not working
Consider using the Struts JSON Plugin
The JSON plugin provides a json result type that serializes actions into JSON.
The content-type must be application/json
Action must have a public “setter” method for fields that must be populated.
Supported types for population are: Primitives (int,long…String), Date, List, Map, Primitive Arrays, other class, and Array of Other class.
Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.
Your actions can accept incoming JSON if they are in package which uses json interceptor or by adding reference to it.
This simplifies the AngularJS HTTP POST request:
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $scope.invoiceDate.toISOString(),
'billProductList': $scope.fproducts,
};
$http({
method: 'POST',
url: 'added-invoice',
data: $scope.bd1,
headers: {'Content-Type': 'application/json'}
}).then(function successCallback(response) {
var data = response.data;
if (data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(response) {
$scope.success = false;
$scope.failure = true;
});
$scope.bd1[billProductList[${index}].${key}] = value; you are overriding value on this line of code
$scope.bd1[billProductList[${index}${index2}].${key}] you can change shape of object as per you need
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value],index2) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}${index2}].${key}`] = value;
});
})
That may be because console.log(index + " " + key + " " + value) is returning correct value as you are getting inside loop.
try to access the below piece of code, after assigning to $scope.bd1:
Object.entries(total).forEach(([key, value]) => {
$scope.bd1[`billProductList[${index}].${key}`] = value;
console.log($scope.bd1[`billProductList[${index}].${key}`]);
});
And I guess $scope.bd1 is not getting updated hence it is not passing value to server side object.

Array empty after pushes were made in get request in Node.js/Express

I am writing a function calling an API to fetch URLs. These are the steps that I wish to accomplish:
Parsing in an array of objects (restaurants) as arguments
For each object, call the Google Search API to get some imageURLs
Store those imageURLs in an array
Add imageURLs as an attribute called imageURLs to each object within the array in the argument
The code is able to log the imageURLs within the GET request, but outside of the request, imageURLs is just an empty array.
var googleSearch = function(restaurants, cb){
console.log("google starts");
const apiKey = google_apiKey;
const cseKey = cseID;
Array.from(restaurants).forEach(function(restaurant){
var keyWord = restaurant.name + " "+ restaurant.location.city
+ " "+ restaurant.location.state + " food";
var googleURL = "https://www.googleapis.com/customsearch/v1?key="+ apiKey +
"&q="+ keyWord +
"&searchType=image" +
"&cx=" + cseKey +
"&num=7" +
"&safe=medium"
;
//image URLs of each restaurants to be displayed in the front end
var imageURLs = [];
request
.get(googleURL,
{
json : true, headers: {
'User-Agent' : 'thaorell'
}
})
.then(function(response){
Array.from(response.items).forEach(function(item){
imageURLs.push(item.link)
});
})
.catch(e => {
console.log(e);
})
restaurant.imageURLs = imageURLs
})
cb(null, restaurants);
}
You're misunderstanding the Promise API:
var googleSearch = function (restaurants, cb) {
console.log("google starts");
const apiKey = google_apiKey;
const cseKey = cseID;
return Promise.all(Array.from(restaurants).map(function (restaurant) {
var keyWord = restaurant.name + " " + restaurant.location.city
+ " " + restaurant.location.state + " food";
var googleURL = "https://www.googleapis.com/customsearch/v1?key=" + apiKey +
"&q=" + keyWord +
"&searchType=image" +
"&cx=" + cseKey +
"&num=7" +
"&safe=medium"
;
return request
.get(googleURL,
{
json: true, headers: {
'User-Agent': 'thaorell'
}
}
)
.then(function (response) {
restaurant.imageURLs = Array.from(response.items).map(function (item) {
return item.link;
});
return restaurant;
})
})
)
.then(restaurants2 => cb(null, restaurants2))
.catch(cb)
}
As you can see you need to wait for all of the requests to finish before you pass the data back to the callback.

Retrieve data from firebase resulting in undefined

I was having this problem when trying to pull from firebase. My database structure as such:
I am trying to pull the merchantName and its relevant branches details:
function getAllMerchant(){
var query = firebase.database().ref('merchants');
return query.once('value').then(data => {
var result = [];
data.forEach(snapshot => {
var merchantData = snapshot.val();
var merchantName = merchantData.merchantName;
var branchName = merchantData.branches.branchName;
var branchAddress = merchantData.branches.branchAddress;
console.log('check ' + merchantName + ' ' + branchName + ' ' + branchAddress);
result.push({merchantName: merchantName, branchName: branchName, branchAddress: branchAddress});
});
return result;
});
resolve(result);
}
However, when I printed out the branchName and branchAddress, I am getting undefined. I managed to print out merchantName though. Any ideas?
Thanks!
You're not iterating over the branches of the merchant.
data.forEach(merchantSnapshot => {
var merchantData = snapshot.val();
var merchantName = merchantData.merchantName;
console.log('check ' + merchantName);
merchantSnapshot.child("branches").forEach(brancheSnapshot => {
var branchName = brancheSnapshot.val().branchName;
var branchAddress = brancheSnapshot.val.branchAddress;
console.log(' ' + branchName + ' ' + branchAddress);
});
});

Getting Uncaught TypeError: Cannot read property 'get' of undefined in spite of the conditionals

I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
var object = results[i];
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The object wasn't being set before the if statement. update, added code from comments
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i]; // <-- THIS NEEDS TO BE BEFORE IF STATEMENT
var imageFl = object.get('ImageFile');
alert(imageFl);
if (imageFl !== '' && typeof imageFl !== 'undefined') {
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});

Categories