Elastic Search JS Function Return value - javascript

Question :
Why is the variable (resultVisitor) returning undefined?
When i log hits inside the function searchVisitors(), the log is returning an array of objects?
Any Ideas?
/* Get passanten telling */
var searchVisitorParams = {
index: 'veenendaal',
type: 'passanten',
size: 100,
body: {
fields: ["Tijdsperiode", "201_WE_Veenendaal", "940_HEMA_Veenendaal"],
query: {
"match_all": {}
},
sort: {
Tijdsperiode: "asc"
}
}
};
function searchVisitors() {
client.search(searchVisitorParams).then(function (body) {
var hits = body.hits.hits;
console.log(hits)
return hits;
});
}
var resultVisitor = searchVisitors();
console.log(resultVisitor)

Return is inside a callback function. I would do something like this:
/* Get passanten telling */
var searchVisitorParams = {
index: 'veenendaal',
type: 'passanten',
size: 100,
body: {
fields: ["Tijdsperiode", "201_WE_Veenendaal", "940_HEMA_Veenendaal"],
query: {
"match_all": {}
},
sort: {
Tijdsperiode: "asc"
}
}
};
function searchVisitors(callback) {
client.search(searchVisitorParams).then(function (body) {
var hits = body.hits.hits;
callback(hits);
});
}
searchVisitors(function(hits){ // Results are inside hits variable
console.log(hits);
// .... Your code ... //
});

Related

How to use a variable with string targeting an object inside an object and add new object?

How to use the variable presentationtitle as key in my else condition within the object given its a string?
I tried if (typeof data.presentations.'(presentationtitle)'
let presentationtitle = 'Test presentation 123'
let variable = {
presentations: {
[presentationtitle] : {
duration: '00:00:00',
}
},
};
chrome.storage.sync.get('presentations', function(data) {
if (typeof data.presentations === 'undefined') {
// if not set then set it
let extensionsettings = {
presentations: {
[presentationtitle] : {
}
},
general: {
setting1: true,
setting2: false
},
};
chrome.storage.sync.set(extensionsettings, () => {
});
}
else {
chrome.storage.sync.get('presentations', function(data) {
if (typeof data.presentations.'(presentationtitle)' === 'undefined') {
// if not set then set it
let presentationtitlesave = {
presentations: {
[presentationtitle] : {
duration: '00:00:00',
}
},
};
chrome.storage.sync.set(presentationtitlesave, () => {
});
}
});
}
Basically I first save an object for extensionsettings (for first time use of the extension opening the popup) and thereafter I want to add presentationtitles into it if they are not present yet (which I extract them from DOM HTML).

Update sales order in NetSuite where order status is pending fulfillment through map/reduce

I need to do following operation performed when my Map/Reduce suiteScript run. It search all sales order where status is Pending Fulfillment, and update their custom checkbox field (field key is my_custom_field_is_proccessed).
How I am trying to do is like below;
/**
* #NApiVersion 2.0
* #NScriptType MapReduceScript
*/
define(['N/search', 'N/record'], function (search, record) {
function getInputData() {
var filter1 = search.createFilter({
name: 'orderstatus',
operator: search.Operator.IS,
values: 'Pending Fulfillment'
});
return search.create({
type: search.Type.SALES_ORDER,
columns: [],
filters: [filter1]
});
}
function map(context) {
try {
var data = JSON.parse(context.value); //read the data
var transId = data.tranid;
var orderstatus = data.orderstatus
var isProcessed = data.my_custom_field_is_proccessed
/*
var order = record.save({
'fromId':data.values['internalid'].value,
'my_custom_field_is_proccessed':true
});
*/
// Update as per below answer
data.forEach(function (order) {
var id = record.submitFields({
type: 'salesOrder',
id: order.internalid,
values: {
my_custom_field_is_proccessed: true
},
options: {
enableSourcing: false,
ignoreMandatoryFields: true
}
});
});
} catch (ex) {
log.error({ title: 'map: error saving records', details: ex });
}
}
function reduce(context) {
// your code here ...
}
function summarize(summary) {
// your code here ...
}
return {
getInputData: getInputData,
map: map,
reduce: reduce,
summarize: summarize
};
});
Can you give try with this code with few changes
/**
* #NApiVersion 2.0
* #NScriptType MapReduceScript
*/
define(['N/search', 'N/record'], function (search, record) {
function getInputData() {
var arrResults = [];
var filter1 = search.createFilter({
name: 'orderstatus',
operator: search.Operator.IS,
values: 'Pending Fulfillment'
});
return search.create({
type: search.Type.SALES_ORDER,
columns: ["internalid"],
filters: [filter1]
});
var id = result.getValue({name: "internalid"});
log.debug({ title: 'id',details: id});
if(id) {
arrResults.push({"id": id, "custom_field_id":custom_field_id});
}
return arrResults;
}
function map(context) {
try {
var data = JSON.parse(context.value); //read the data
var recordId = data.id;
var transId = data.tranid;
var orderstatus = data.orderstatus
var isProcessed = data.my_custom_field_is_proccessed
var recordUpdateData = {
"type": record.Type.SALES_ORDER,
"id": recordId,
"values": {}
};
recordUpdateData["values"][custom_field_id] = 10;
record.submitFields(recordUpdateData);
} catch (ex) {
log.error({ title: 'map: error saving records', details: ex });
}
}
function reduce(context) {
// your code here ...
}
function summarize(summary) {
// your code here ...
}
return {
getInputData: getInputData,
map: map,
reduce: reduce,
summarize: summarize
};
});
Use record.submitFields instead of record.save.
var id = record.submitFields({
type: recordType,
id: id,
values: {
fieldId: value
},
options: {
enableSourcing: false,
ignoreMandatoryFields : true
}
});

Make the local variable to global in extjs

How to make local variable to global?
Ext.define('A.view.Management', {
extend: 'Ext.container.Container',
requires: [
'A.store.Management',
],
border: false,
chart: null,
hrer: [],
initComponent: function () {
var me = this;
me.jobStore2 = Ext.create('O2a.store.Management');
Ext.Ajax.request({
url: utils.createUrl('api', 'ard-read'),
async: true,
callback: function(opts, success, response) {
try {
if (success) {
var output = App.decodeHttpResp(response.responseText);
const data = output.data;
let myArr = [];
data.map((date) =>
myArr = Object.keys(date).filter(key => key != 'DATE'));
me.hrer =myArr;
console.log(me.hrer);
if (output.success) {
//return output.success;
} else {
//return output.error;
}
} else {
//return 'Unknown Reason';
}
} catch (ex) {
//return ex;
}
}
});
console.log(me.hrer);
I want to take hrer array to outside. When I console.log it outside the ajax request I am getting an empty array which I have defined as globally. I couldn't pass the values which getting inside the ajax request to outside
In ExtJS 4, we used to do:
Ext.define('A.store.SharedData', {
singleton: true,
foo: 'bar',
johnDoeAge: 42,
hrer: []
});
Then require it in whichever component you want to use and consume it like:
Ext.define('A.view.Management', {
extend: 'Ext.container.Container',
requires: [
'A.store.Management',
'A.store.SharedData'
],
initComponent: function () {
var me = this;
A.store.SharedData.hrer = [1, 2, ...];
...
}
...
});

Strange behavior in javascript argument inside a global Object

there is a strange behavior in an argument inside a Global Javascript object:
I need to test my code with jasmine.js, but I canĀ“t pass the expected value to the argument always return undefined in jasmine test.
//My model
myGlobalObject = function(){
_myCart = function(){
return {
total : 0,
products : []
}
}
return {
init: function(strangeArgument){
console.log(strangeArgument) //this return undefined in jasmine test
},
myCart : _myCart,
addProduct : function(Products){
return _myCart()
},
.....
}
}
The test:
const c{
empty : {
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
},
products: []
}
}
beforeEach(() => {
this.instance = myGlobalObject();
this.instance.init();
this.productWithoutQuantity = Object.assign({}, _.productA);
delete this.productWithoutQuantity.quantity;
this.productWithQuantity = Object.assign({}, _.productB);
});
test(`the cart should be empty`, () => {
expect(this.instance.getCart()).toEqual(c.empty);
});
.... more tests
And my main js:
var e = myGlobalObject();
var initialState = function (){
return {
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
},
products: []
}
}
e.init(initialState);
What its wrong?
Although I fail to completely understand the intent of the OP here, following is my take on the question
_myCart can be a local variable because it doesn't seem to serve any greater purpose, atleast from the code provided by OP
The call to instance.init can be with empty parenthesis or with a legitimate variable- depends on what OP is trying to achieve here.
I've included both main.js code snippet as well as testVariable.instance.init(); (on a simple note its undefined if it is undefined anyway as commented by #Bergi)
See it in action here
myGlobalObject = function() {
this._myCart = function() {
return {
total: 0,
products: []
}
}
return {
init: function(strangeArgument) {
console.log(strangeArgument)
},
myCart: this._myCart,
addProduct: function(Products) {
return this._myCart()
}
}
}
var e = myGlobalObject();
var initialState = function() {
return {
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
},
products: []
}
}
e.init(initialState);
describe('ajax test suite', function() {
var testVariable = {}
var c = {
empty: {
total: 0,
products: []
}
}
beforeEach(function() {
testVariable.instance = myGlobalObject();
testVariable.instance.init("hello");
testVariable.instance.init();
});
it('the cart should be empty', function() {
expect(testVariable.instance.myCart()).toEqual(c.empty);
});
});

unable to access function from another function using this within same object

I have the following:
$scope.option = {
generateID:function(){
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
},
values : [
{id:this.generateId()},
{id:this.generateId()},
{id:this.generateId()},
{id:this.generateId()}
],
markCorrect : function(option){
},
remove:function(option)
{
this.values = this.values.filter(function(value){return value.id!=option.id})
}
}
I always get a this.generateId is not a function error. I am pretty sure that i am missing something fundamental here!
It may be better to store the id generator function in a separate function so it is easier to reference:
function generateId = function() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
}
$scope.option = {
generateID: generateId,
values : [
{id: generateId()},
{id: generateId()},
{id: generateId()},
{id: generateId()}
],
markCorrect : function(option){
},
remove:function(option)
{
this.values = this.values.filter(function(value){return value.id!=option.id})
}
}
The primary issue is that you're trying to access properties of $scope.option in the middle of declaring it. Try doing something like this instead:
$scope.option = (function () {
function generateId () {
/* logic */
}
return {
values: [
{id: generateId()}
// ...
],
markCorrect: function () {},
remove: function () {}
};
}) ();
This is the 'revealing module pattern', i.e. a function that returns an object forming a closure on some other data or functionality.
There is a typo; rename generateID to generateId.

Categories

Resources