I am doing an API call and data fetching with Fetch function on a platform listing different products with their data identified by attributes, here I am trying to fetch multiple attributes of a specific category of product, each product is identified by a unique serial number, which serves as my entry key to retrieve product data.
Or the attributes that I retrieve do not exist for certain products, either the field exists but the data is null, or the field is not filled in on the platform for this product.
I neutralize nulls with the formula you can see on my script but it doesn't always work, I would like to know if I can make my API even more dynamic, i.e. retrieve attributes only when they exist and when the presence of a null does not block the API call.
function GetAllProduct() {
var token=ConnectAlkemics();
//Logger.log(token);
var headers ={
"accept": "*/*",
"accept-language": "fr",
'Authorization' : 'Bearer ' + token,
'cache-control': 'no-cache',
'content-type': 'application/json;charset=UTF-8',
'expires': '-1',
'pragma': 'no-cache',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'x-alk-priority': '9'
};
var options ={
'method' : "GET",
"headers" : headers
};
var source =SpreadsheetApp.getActive().getSheetByName("GTIN");
var ss =SpreadsheetApp.getActive().getSheetByName("RESULTATS");
ss.clear();
// var dico=CreerDicoHeader();
//retrieving list of attribute
var lastRow = source.getLastRow();
var listeAttribut = "";
var listeChamp = "";
var tabChamp = [];
var index = 0;
for(var i = 2; i <= lastRow; i++ ){
//Logger.log(i);
if(source.getRange(i, 3).getValue() != ""){
tabChamp[index] = source.getRange(i, 2).getValue();
index +=1;
if(listeAttribut == ""){
listeAttribut = source.getRange(i, 3).getValue();
listeChamp = source.getRange(i, 2).getValue();
}
else{
listeAttribut = listeAttribut + "," + source.getRange(i, 3).getValue();
listeChamp = listeChamp + "," + source.getRange(i, 2).getValue();}
}
}
var total=0;
var debut=2;
var moregtin=true
var lignegtin=1;
var colonnes=[
"GTIN",
"Libelle long",
"Fournisseur",
"Catégorie du produit",
"Code Tiers",
"Cycle de vie",
"Maturité commande Galec",
"Maturité direct magasin" ,
"Maturité Commande SCABEL",
"Maturité complémentaire Galec",
"Maturité complémentaire Direct Magasin",
"Maturité complémentaire Scabel",
"Maturité Animation Digitale",
"Maturité Digitale",
"Maturité Entité Leclerc",
"Type d'unité",
"Marque Commerciale",
"Appellation viticole ou région d'origine",
"Complément d'appellation(N)",
"Packaging vin",
"Contenu net",
"Description des saveurs du vin",
"Type de champagne(N)",
"Viticulture(N)",
"Couleur du Vin",
"Millésime",
"Terroirs et sol(N)",
"Région Viticole",
"Durée du potentiel de maturation",
"Echelle de fruit",
"Echelle de personnalité",
"Dégustation robe",
"Dégustation nez",
"Type de vendange(N)",
"Dégustation bouche",
"Type d'appellation du vin",
"Allergènes avérés",
"Type d'allergène",
"Degré d'alcool",
"Teneur en sucre",
"Description du cépage",
"Accords mets et vins",
"Occasions particulières",
"Températures de dégustation (en °c)",
"Potentiel de garde",
"Code de nomenclature douanière",
"Code produit accise france",
"Libellé fiscal",
"Pays d'origine",
"Type de paiement des droits d'alcools",
"Image Face du produit",
"Image Arrière du produit",
];
var colonnematurite=6; //Colonnes
for(i=0;i<colonnes.length;i++) {
ss.getRange(1,i+1).setValue(colonnes[i]);
}
//for(i=0; i<tabChamp.length; i++){
// ss.getRange(1,i+1).setValue(tabChamp[i]);
//Logger.log(tabChamp[i]);
//}
while (moregtin==true)
{
var fini=false;
var nbgtin=0;
var lesgtin="";
var produits =[];
while ((source.getRange(lignegtin,1).getValue()!="") && (nbgtin<50)) //paquets de 50 GTINs
{
if (lesgtin!="")
lesgtin=lesgtin+",";
lesgtin=lesgtin+source.getRange(lignegtin,1).getValue().toString().replace(/\s+/g," ").trim();
lignegtin=lignegtin+1;
nbgtin=nbgtin+1;
}
if (lesgtin=="")
{
moregtin=false;
fini=true;
}
else
{
var limit=200;
var next_page='';
var lastparam='';
var params =lastparam + 'status_shared_from=4' + lesgtin + '&filter_source_include=uuid,gtin,namePublicLong,namePublicShort,isSharedFrom.sourceOrganization.nameLegal,endAvailabilityDateTime,supplierId,business_processes,brand.description,lastOrderDateTime,isUserLabeledByName,lifeCycle,typePackaging,isConsumerUnit,isBaseUnit,isDisplayUnit,assets,pictures,exportables'
var params =lastparam + '&filter_product_languages=fr&filter_gtins_in=' + lesgtin + '&filter_source_include=' + listeAttribut
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
}
while (fini==false) {
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
var url='https://apis.alkemics.com/public/v1/products?'+lesparams;
//Logger.log(url);
var content =UrlFetchApp.fetch(url, options);
//Logger.log(content);
//Logger.log(content.getResponseCode())
if (content.getResponseCode() ==200) {
var retour =JSON.parse(content.getContentText());
next_page=retour.next_page;
var data=retour.data;
for(i=0; i<data.length;i++) {
var produit=data[i]; // Un produit au format JSON
var libellelong="";
try
{
libellelong=produit.namePublicLong[0].data;
}
catch(e) {
libellelong="";
//libelle="NA"
}
var libellecourt="";
try
{
libellecourt=produit.namePublicShort[0].data;
}
catch(e) {
libellecourt="";
//libelle="NA"
}
var maturite={}
for(k=0;k<produit.business_processes.length;k++)
{
maturite[produit.business_processes[k].label]=(produit.business_processes[k].requested==false?"":(produit.business_processes[k].status==true?"OK":"KO"));
}
var listematurite={}
for(k=0;k<produit.business_processes.length;k++)
{
listematurite[k]=produit.business_processes[k].label;
}
var marque=""
if ("brand" in produit) {
if ("description" in produit.brand)
marque=produit.brand.description;
}
var occasionwhine=""
if (" occasions" in produit) {
if("occasion" in produit.occasions[0])
occasionwhine = produit.occasions[0].occasion.label
}
var pairing=""
if (" pairingsTypes" in produit) {
if("pairingsType" in produit.pairingsTypes[0])
pairing = produit.pairingsTypes[0].pairingsType.label
}
var mediaface= ""
if (" assets" in produit) {
if("pictures" in produit.assets)
if("exportables" in produit.assets.pictures[0])
mediaface= produit.assets.pictures[0].exportables[0].uniformResourceIdentifier
}
var mediaback
if (" assets" in produit) {
if("pictures" in produit.assets)
if("exportables" in produit.assets.pictures[2])
mediaback= produit.assets.pictures[2].exportables[0].uniformResourceIdentifier
}
//var ConsumerUnit = (produit.isConsumerUnit == false ?"":(produit.isBaseUnit==true?"UC":"LOT"))
//var Presentoir = (produit.isDisplayUnit == true ? produit.typePackaging.label : "")
var ligne=[
produit.gtin,
libellelong,
produit.isSharedFrom[0].sourceOrganization.nameLegal,
produit.kind != null? produit.kind.label: ' ',
produit.supplierId,
produit.lifeCycle,
//(produit.endAvailabilityDateTime==null?"":TIMESTAMP_TO_DATE(produit.endAvailabilityDateTime)),
//produit.isUserLabeledByName,
maturite[tabChamp[colonnematurite]],
maturite[tabChamp[colonnematurite+1]],
maturite[tabChamp[colonnematurite+2]],
maturite[tabChamp[colonnematurite+3]],
maturite[tabChamp[colonnematurite+4]],
maturite[tabChamp[colonnematurite+5]],
maturite[tabChamp[colonnematurite+6]],
maturite[tabChamp[colonnematurite+7]],
maturite[tabChamp[colonnematurite+8]],
produit.typePackaging.label,
marque,
produit['alcoholicBeverageSubregionText'],
produit['alcoholicBeverageAdditionalAppellationDetailsText'],
produit.leclercWinePackagingTypeCode != null? produit.leclercWinePackagingTypeCode.label : ' ',
produit.netWeight[0] != null? produit.netWeight[0].data: ' ',
produit.wineTastingDescriptionList[0] != null?
produit.wineTastingDescriptionList[0].wineTastingCode.label : ' ',
produit.wineCategoryCode != null? produit.wineCategoryCode.label: ' ',
produit.vintnerTextList,
produit.colorGroup != null? produit.colorGroup.label: ' ',
produit.vintage,
produit.vineyardRegion != null? produit.vineyardRegion.label: ' ',
produit.leclercFrenchVineyardRegionCode != null? produit.leclercFrenchVineyardRegionCode.label: ' ',
produit.wineAgeingPotentialDurationCode != null? produit.wineAgeingPotentialDurationCode.label: ' ',
produit.wineFruitExpressionNoteNumber,
produit.wineAromasExpressionNoteNumber,
produit.wineTastingRobeDescriptionText[0] != null? produit.wineTastingRobeDescriptionText[0].data: ' ',
produit.wineTastingNoseDescriptionText[0] != null? produit.wineTastingNoseDescriptionText[0].data: ' ',
produit['grapeHarvestingDescriptionText'].data,
produit.wineTastingMouthDescriptionText[0] != null? produit.wineTastingMouthDescriptionText[0].data:' ',
produit.wineCategoryCode != null? produit.wineCategoryCode.label: ' ',
produit.allergens[0] != null? produit.allergens[0].data : ' ',
produit.allergenTypeList,
produit.ratioAlcohol,
produit.sugarContent != null? produit.sugarContent.label: ' ',
produit.varietalDesignationDescriptionText[0] != null? produit.varietalDesignationDescriptionText[0].data:' ',
pairing,
//produit.pairingsTypes[0] != null? produit.pairingsTypes[0].pairingsType.label: ' ',
occasionwhine,
//produit.occasions[0].occasion != null? produit.occasions[0].occasion.label: ' ' , //+ "," + produit.occasions[1],
produit.tempConsumption[0] != null? produit.tempConsumption[0].data: ' ',
produit.wineAgeingPotentialDurationCode != null? produit.wineAgeingPotentialDurationCode.label : ' ',
produit.importEuropeanClassification,
produit.cpaFranceCode.label,
produit.taxLabelList[0] != null? produit.taxLabelList[0].taxLabelCode.label: ' ',
produit.countryOfOriginList[0] != null? produit.countryOfOriginList[0].countryOfOriginCode.label: ' ',
produit.alcoholicBeveragePaymentTypeCode != null? produit.alcoholicBeveragePaymentTypeCode.label: ' ',
mediaface,
mediaback,
//produit.assets.pictures[0].exportables[0] != null? produit.assets.pictures[0].exportables[0].uniformResourceIdentifier: ' ',
// produit.assets.pictures[2].exportables[0] != null? produit.assets.pictures[2].exportables[0].uniformResourceIdentifier: ' ',
//ConsumerUnit,
//Presentoir
];
produits.push(ligne);
total=total+1;
}
}
else {
Logger.log('Error in GET /contents/{contentid}')
}
I have a loop running for each selected checkbox in Javascript / Jquery.
Inside this loop I call an async function that will return a Tile Layer(Image).
I have to pass to this function a parameter called checkboxPermanent.
After this function is called the variable checkboxPermanent changes its value, not sure why.
In the sequence it calls a similiar function but now passing the same variable but with the wrong parameter value.
$('#exec-perm').on('click', function () {
var checkboxPermanent;
$('#checks-perm input').each(async function () {
checkboxPermanent = $(this).attr('value');
isChecked = $(this).prop('checked');
permanent = permanent_layers[checkboxPermanent] // começa com valor undefined, no próximo loop passa a conter um objeto para que possa cair na codição 1
pixel_permanent = pixel_permanent_layers[checkboxPermanent]
if (permanent) {
if (!isChecked) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
} else if (isChecked && state_faz == faz_value && state_ano_safra == ano_safra_value && state_profundidade == profundidade_value) {
//map.addLayer(permanent)
//map.addLayer(pixel_permanent)
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
} else if (isChecked && (state_faz != faz_value || state_ano_safra != ano_safra_value || state_profundidade != profundidade_value)) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
} else if (isChecked) {
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
//console.log(checkboxPermanent)
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
if (checkboxPermanent == 'altimetria') {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
} else {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
}
});
})
If I console.log(checkboxPermanent) before wmswmsPermRasterCall(). It will return the right value. If I console.log(checkboxPermanent) right after wmswmsPermRasterCall() is called it gets a different value..
async function wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value) {
//var colorRampSLD = getStyles(faz_value, checkboxPermanent)
if (checkboxPermanent == 'altimetria') {
var raster_name = checkboxPermanent + '_' + faz_value
getColors = await getStyles(faz_value, checkboxPermanent)
var colorEnv = '';
for (var j = 0; j < getColors.length; j++) {
if (j + 1 >= getColors.length) {
colorEnv += 'c' + j + ':' + getColors[j]
} else {
colorEnv += 'c' + j + ':' + getColors[j] + ';'
}
}
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + raster_name,
transparent: true,
format: 'image/png',
}).setParams({
env: colorEnv
})
} else {
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value,
transparent: true,
format: 'image/png',
})
}
}
What Am I missing here?
Check here:
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
This function is async, it will run outside of your function, your code will continue before wmsPermRasterCall is finished.
You need to wait for the result of wmsPermRasterCall using await:
console.log(checkboxPermanent)
permanent = await wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
Your code will halt until wmsPermRasterCall is finished.
I have a function inside of an immediately invoked function expression and I want to be able to access that function globally without lexically scoping it that way.
How can I access this "private" function through a namespace called "App"?
indew.html:
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="filtering.js"></script>
</head>
<body>
<article>
<p>
Computer graphics is widespread today. Computer imagery is found on televi
surfaces, illumination sources, and so forth, perhaps with a dynamic (time) component".[3]
</p>
</article>
<section id="result"></section>
<script>
App.showOccurenceFiltering(); // here is my wrong call
</script>
</body>
</html>
js script :
var App = (function () {
function showOccurenceFiltering() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
}(App));
so i got an error of a miss call like shows the capture :
how should i resolve my problem ??
You'll need to expose the function to the global scope. You can do this with a namespace, like this:
(function () {
function showOccurenceFiltering() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
// Prepare a "dummy" object
var obj = {};
// Attach the private function to this object
obj.showOccurenceFiltering = showOccurenceFiltering;
// Attach the dummy object to the global scope in a controlled namespace:
window.App = obj;
}());
Then you can access the function like this:
App.showOccurenceFiltering();
You could do the following:
var App = (function(){
var obj = {};
obj.showOccurenceFiltering = function() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
return obj;
}());
Your App variable remains undefined because the Immediately Invoked Function Expression does not return a value.
Instead, define App as an object literal, as follows:
var App = {
showOccurenceFiltering: function() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
};
Now your call will be valid.
I tried to put 3 variations are included:
empty
version IS NOT NULL AND
version = ' + criteria.version + ' AND
I need use escape
Help please
this code is wrong, but for understanding I need like this:
function getCriteria(criteria){
var ver = '';
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ' + criteria.version + ' AND';
}
return mysql.getConnection((conn) => {
return conn.queryAsync('SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ? create_timestamp < "2017-02-16 13:34:40"', [ver]).then............
You could build the query text using regular string handling, but still use the parameterization for the case where you need it;
function getCriteria(criteria) {
var ver = '';
var parms = []
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ? AND';
parms = [criteria.version]
}
return mysql.getConnection((conn) => {
return conn.queryAsync(
'SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ' + ver + ' create_timestamp < "2017-02-16 13:34:40"', parms)
.then............