Where to put http get call inside a javascript promise - javascript

I am using Elasticsearch and AngularJS to build a small search application. I'm trying to use Angular UI Bootstrap Typeahead to implement an autocomplete feature using the http.get call for asynchronous results and am not exactly sure where to put it?.... still learning ES and Angular.
Where would I put this http.get call inside this js promise code?
http.get code:
return $http.get('localhost:9200/bigtestindex/doc/_search', {
params: {
"query": {
"match": {
"content.autocomplete": {
"query": query,
"default_operator": "and"
}
}
}
}
}),
Javascript promise code:
this.getSuggestions = function(query) {
var deferred = $q.defer();
var terms = query.split(' '),
baseTerms = terms.length === 1 ? '' : terms.slice(0, -1).join(' ') + ' ',
lastTerm = terms[terms.length - 1].toLowerCase();
esClient.search({
index: 'bigtestindex',
body: {
"query": {
"simple_query_string": {
"fields": ['title'],
"query": baseTerms + '(' + lastTerm + '|' + lastTerm + '*)',
"default_operator": "and"
}
},
"suggest": {
"text": query,
"phraseSuggestion": {
"phrase": {
"field": "title",
"direct_generator": [{
"field": "title",
"suggest_mode": "popular",
"min_word_length": 3,
"prefix_length": 2
}]
}
}
},
"size": 5,
"_source": ["content"]
}
}).then(function(es_return) {
deferred.resolve(es_return);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
};
I am pretty sure in goes in the body somewhere just not sure where... I can't get it to work.

I suppose, your controller code could look like this:
function searchController(esClient)
{
var ctl = this;
ctl.suggestions = [];
this.getSuggestions = function(query) {
var terms = query.split(' '),
baseTerms = terms.length === 1 ? '' : terms.slice(0, -1).join(' ') + ' ',
lastTerm = terms[terms.length - 1].toLowerCase();
esClient.search({
index: 'bigtestindex',
body: {
"query": {
"simple_query_string": {
"fields": ['title'],
"query": baseTerms + '(' + lastTerm + '|' + lastTerm + '*)',
"default_operator": "and"
}
},
"suggest": {
"text": query,
"phraseSuggestion": {
"phrase": {
"field": "title",
"direct_generator": [{
"field": "title",
"suggest_mode": "popular",
"min_word_length": 3,
"prefix_length": 2
}]
}
}
},
"size": 5,
"_source": ["content"]
}
}, function(err, es_return) {
if(err) {
//Handle error or do nothing
return;
}
ctl.suggestions = es_return;
});
};
}

Related

Boolean value from NodeJS webservice is not boolean when using in test

I called a NodeJS webservice :
request({
url: "http://10.210.210.41:3001/trackable/lastPos",
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
async.forEachOf(body, function (vehiculeJSON, cleJSON, cbVehiculeJSON) {
var tabFlotte = vehiculeJSON.flotte;
if (tabFlotte.length > 0) {
var dbJSON = rows.find(function(row) {
return row.num_tag_ip == cleJSON;
});
if (dbJSON != undefined) {
var num_tag_ip = cleJSON, etat = vehiculeJSON.state, coordinates = vehiculeJSON.position, immatriculation = dbJSON.immatriculation, lib = dbJSON.lib, msisdn = dbJSON.msisdn;
if (vehiculeJSON.is_outofarea == true) { // here is the test
...
}
}
}
cbVehiculeJSON();
}, function () {
...
});
} else {
...
}
});
It returns values like this :
{
"TMA0224": {
"zone": 161,
"fixed_at": "2019-12-03T09:55:49.000Z",
"flotte": [
{
"type": "fleet",
"id": "GAN.TELMAPROPRE"
},
{
"type": "fleet",
"id": "TMA"
},
{
"type": "fleet",
"id": "TMA.DVI-MOTOS"
},
{
"type": "fleet",
"id": "TMA.TELMA"
}
],
"state": "MOV",
"numero_tag_ip": "TMA0224",
"immatriculation": "1271TBH",
"ignition": false,
"mileage": 3263,
"heading": 313,
"speed": 2,
"is_outofarea": true,
"position": {
"latitude": -18.90895,
"longitude": 47.536675
}
},
...
}
But at runtime the test never enters the "if" test. But when I replace the test by vehiculeJSON.is_outofarea == "true" then the test succeeds ! So why is the json supposed boolean value transformed to String ?
Try this instead :
if (!!vehiculeJSON.is_outofarea) {
...
}
It should work whether it is a string or a bool.

How to get object values in a specified manner by with keys and values

i wanted print the string in a specifed manner but i'm not finding any convenient solution.
I'm expecting below result:
<h1>new_data</h1>
<h4>print:</h4> <span>inv_val_ads_details_brand,auth_sign</span>
<h4>report:</h4> <span>value_ads_report,per_day_volume_billing</span>
<h4>media:</h4> <span>media,auto_generated_media</span>
<hr>
<h1>old_data</h1>
<h4>media:</h4> <span>meta_data</span>
<h4>order:</h4> <span>cg_counter,sub_vertical</span>
here is what i have tried:
var data = {
"new_data": {
"print": {
"inv_val_ads_details_brand": true,
"auth_sign": false
},
"report": {
"value_ads_report": true,
"per_day_volume_billing": false
},
"media": {
"media": false,
"auto_generated_media": true
}
},
"old_data": {
"media": {
"meta_data": false
},
"order": {
"cg_counter": true,
"sub_vertical": false
}
}
};
var str = '';
Object.keys(data).map(function(key) {
str += '<h1>'+key+'</h1>';
console.log('main heading...',key);
Object.keys(data[key]).map(function(val){
console.log('values',val);
});
});
Question: snippet 1 output i'm expecting
Please help me thanks in advance !!!!!
As you don't return anything, use forEach instead of map, and doing something like this would give the output you asked for
Stack snippet
var data = {
"new_data": {
"print": {
"inv_val_ads_details_brand": true,
"auth_sign": false
},
"report": {
"value_ads_report": true,
"per_day_volume_billing": false
},
"media": {
"media": false,
"auto_generated_media": true
}
},
"old_data": {
"media": {
"meta_data": false
},
"order": {
"cg_counter": true,
"sub_vertical": false
}
}
};
var str = '';
Object.keys(data).forEach(function(key) {
str += '<h1>' + key + '</h1>';
Object.keys(data[key]).forEach(function(val) {
str += '<h4>' + val + ':</h4>';
Object.keys(data[key][val]).forEach(function(val2, idx) {
if (idx > 0) str += ',';
str += '<span>' + val2 + '</span>';
});
});
});
document.body.innerHTML = str;

Dialogue.Directive Not Working When emiting the handler ?

After A dialogue is completed and its confirmationStatus is changed to confirmed than i emit another dialogue directive ./ intent but its directive dosent work and it directly jumps to emit and ends
code :-
const handlers = {
'LaunchRequest': function () {
this.response.speak(welcomeOutput).listen(welcomeReprompt);
var userID = this.event.session.user.userID;
console.log(userID);
this.emit(':responseReady');
},
'createOrder': function () {
var filledSlots = delegateSlotCollection.call(this);
this.emit(':tell','Create Order Ended');
},
'addOrder': function () {
var filledSlots = delegateSlotCollectionSecond.call(this);
},
'AMAZON.HelpIntent': function () {
speechOutput = "";
reprompt = "";
this.response.speak(speechOutput).listen(reprompt);
this.emit(':responseReady');
},
'AMAZON.YesIntent': function () {
this.emit("Yes Triggered");
},
'AMAZON.NoIntent': function () {
this.emit("NO Triggered");
},
'AMAZON.CancelIntent': function () {
speechOutput = "Okay Your Request is Cancelled";
this.response.speak(speechOutput);
this.emit(':responseReady');
},
'AMAZON.StopIntent': function () {
speechOutput = "";
this.response.speak(speechOutput);
this.emit(':responseReady');
},
'SessionEndedRequest': function () {
var speechOutput = "";
this.response.speak(speechOutput);
this.emit(':responseReady');
},
'AMAZON.FallbackIntent': function () {
console.log('AMAZON FALL BACKINTENT');
},
'Unhandled': function () {
console.log("Unhandled");
},
};
exports.handler = (event, context) => {
var alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
// To enable string internationalization (i18n) features, set a resources object.
//alexa.resources = languageStrings;
alexa.registerHandlers(handlers);
alexa.execute();
};
// END of Intent Handlers {} ========================================================================================
// 3. Helper Function =================================================================================================
function delegateSlotCollection() {
console.log("in delegateSlotCollection");
console.log("current dialogState: " + this.event.request.dialogState);
if (this.event.request.dialogState === "STARTED") {
var updatedIntent = this.event.request.intent;
this.emit(":delegate", updatedIntent);
} else if (this.event.request.dialogState !== "COMPLETED") {
console.log("in not completed");
this.emit(":delegate")
} else {
if (this.event.request.intent.confirmationStatus === 'CONFIRMED'){
this.emit('addOrder');
}
return this.event.request.intent;
}
}
function delegateSlotCollectionSecond() {
console.log("in delegateSlotCollection");
console.log("current dialogState: " + this.event.request.dialogState);
if (this.event.request.dialogState === "STARTED") {
var updatedIntent = this.event.request.intent;
this.emit(":delegate", updatedIntent);
} else if (this.event.request.dialogState !== "COMPLETED") {
console.log("in not completed");
this.emit(":delegate")
} else {
if (this.event.request.intent.confirmationStatus === 'CONFIRMED'){
Console.log("Vegeta");
console.log(this.event.request.intent.confirmationStatus);
}
return this.event.request.intent;
}
}
This Is the code that i am using so when first createOrder Dialogue is completed it ask for confirmation and when i say yes than add order is emited but its dialogue directive didnt work it directly emits the statement so how to solve tghis problem ?
'createOrder': function () {
this.emit(':ask','tell me item name');
},
'productIntent': function(){
this.event.request.intent.slots.product.value //have an intent and slot for product
this.attributes['anyName'] = "product"; put product in session
this.emit(':ask','tell me quantity');
}
'quantityIntent': function(){
this.event.request.intent.slots.quantity.value //have an intent and slot for quality
this.attributes['anyName'] = "quantity"; put quantity in session
this.emit(':ask','do you want to add more item');
}
'Amazon.yesIntent': function () {
this.emit("createOrder"); //repeat
},
//handle no intent by retrieving all data and making your order
let retriveddata = this.attributes['anyName'];
You get the idea.
This way you won't lose the data between intents unless the session ends.
{
"interactionModel": {
"languageModel": {
"invocationName": "hello order",
"intents": [
{
"name": "AMAZON.FallbackIntent",
"samples": []
},
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": []
},
{
"name": "CreateOrder",
"slots": [],
"samples": []
},
{
"name": "ProductIntent",
"slots": [
{
"name": "productType",
"type": "products"
}
],
"samples": [
"{productType}"
]
},
{
"name": "QuanityIntent",
"slots": [
{
"name": "quantiyValue",
"type": "AMAZON.NUMBER"
}
],
"samples": [
"{quantiyValue}"
]
},
{
"name": "AMAZON.YesIntent",
"samples": []
},
{
"name": "AMAZON.NoIntent",
"samples": []
}
],
"types": [
{
"name": "products",
"values": [
{
"name": {
"value": "burger"
}
},
{
"name": {
"value": "pizza"
}
}
]
}
]
}
}
}

How to apply where condition to backbone query

I'm building an app with Appcelerator.
I use Backbone to get data from database.
So I have build this code to get data from database:
var collection = Alloy.createCollection("SocialHistoryDAO");
collection.fetch();
Now I want to apply a where at this collection. So I use this code:
collection.where(id : 5);
Then this code works, but now I want to apply this filter:
"WHERE ID != 5";
It is possible to do this?
EDIT:
this is my SocialHistoryDAO model:
exports.definition = {
config: {
columns: {
"ID": "INTEGER PRIMARY KEY AUTOINCREMENT",
"IdOmnia": "INTEGER",
"DateStart": "text",
"DateEnd": "text",
"Quantity": "decimal",
"Code": "text",
"CodeSystem": "text",
"DisplayName": "text",
"DisplayNameTarget": "text",
"UnityMeasure": "text",
"StateID": "INTEGER"
},
adapter: {
type: "sql",
collection_name: "SocialHistoryDAO",
idAttribute: "ID"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
destroyAll : function(opt) {
var db = Ti.Database.open(this.config.adapter.db_name);
db.execute("DELETE FROM " + this.config.adapter.collection_name);
db.close();
this.models = [];
if (!opt || !opt.silent) { this.trigger("reset"); }
return this;
}
});
return Collection;
}
};
If you're using Backbone, then you're also using Underscore (or LoDash).
This can be accomplished using either:
var newArray = _.filter(collection.models, function(model) { return model.get('ID') != 5; });
or
var newArray = _.reject(collection.models, function(model) { return model.get('ID') == 5; });

JQuery parsing only portion of JSON

Run into issue with parsing fairly complex JSON data.
What I am trying to achieve is parse the json data, extract address information and populate that in the typeahead drop down list.
JSON Data:
"{
"Version":"2.0.20",
"ResultCode":"XS02",
"ErrorString":"",
"Results":
[
{"Address":
{"AddressLine1":"300 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501","CountrySubdivisionCode ":"US-AK","AddressKey":"99501118273","SuiteName":"Apt","SuiteCount":3,"SuiteList":["","Apt A","Apt B"],"PlusFour":["1182","1182","1182"]}
},
{"Address":
{"AddressLine1":"240 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1150","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115040","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
{"Address":
{"AddressLine1":"308 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1152","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115208","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
{"Address":{"AddressLine1":"301 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1151","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115101","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
]
}"
I only need to parse all the Addresses and extract AddressLine1 + City + State + PostalCode
JQuery:
$('#taquery').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'states',
displayKey: 'value',
source: function (query, process) {
return $.ajax({
url: "/addressLookup",
type: 'get',
data: { query: query },
dataType: 'json',
success: function (data) {
return typeof data == 'undefined' ? false : processResult(data);
}
});
}
});
var processResult = function (data) {
var addArray = $.makeArray(data.Results);
$.map(addArray, function (item, i) {
return (formatAddressJson(item.Address, i));
});
};
var formatAddressJson = function (addr, idx) {
var rtn;
rtn = {
fullAddress: addr.AddressLine1 + ', ' + addr.City + ', ' + addr.State + ', ' + addr.PostalCode,
addrLine1: addr.AddressLine1,
city: addr.City,
state: addr.State,
zip: addr.PostalCode.substring(0, 5),
idx: idx
};
return rtn;
}
Error:
jquery-1.10.2.min.js:4 Uncaught TypeError: Cannot use 'in' operator to search for '2548' in {"Version":"2.0.20","ResultCode":"XS02","ErrorString":"","Results":[{"Address":{"AddressLine1":"300 1/2 E Manor
var data = JSON.parse(response);
var addresses = data.results.reduce(function(agg, cur, idx) {
agg.push(formatAddress(cur.Address, idx)
return agg;
}, []);
function formatAddress(adr, idx) { //...your method }
// now you can loop over addresses array and access each.
addresses.forEach(function(addressObject) { console.log(addressObject) });
this code should make it work, you should use reduce method instead of map, and you do not need jquery to accomplish this.
EDIT
var JSON_FROM_SUCCESS_FUNCTION = {
"Version": "2.0.20",
"ResultCode": "XS02",
"ErrorString": "",
"Results": [{
"Address": { "AddressLine1": "300 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501118273", "SuiteName": "Apt", "SuiteCount": 3, "SuiteList": ["", "Apt A", "Apt B"], "PlusFour": ["1182", "1182", "1182"] }
}, {
"Address": { "AddressLine1": "240 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1150", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115040", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
}, {
"Address": { "AddressLine1": "308 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1152", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115208", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
}, {
"Address": { "AddressLine1": "301 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1151", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115101", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
}]
};
/*
$('#taquery').typeahead({
hint: true,
highlight: true,
minLength: 3
}, {
name: 'states',
displayKey: 'value',
source: function (query, process) {
return $.ajax({
url: "/addressLookup",
type: 'get',
data: { query: query },
dataType: 'json',
success: function (data) {
return typeof data == 'undefined' ? false : processResult(data);
}
});
}
});
*/
function processResult(data) {
return data.Results.reduce(function(agg, cur, idx) {
agg.push(formatAddress(cur.Address, idx));
return agg;
}, []);
};
function formatAddress(addr, idx) {
var fullAddress = addr.AddressLine1 + ', ' + addr.City + ', ' + addr.State + ', ' + addr.PostalCode;
return {
fullAddress: fullAddress,
addrLine1: addr.AddressLine1,
city: addr.City,
state: addr.State,
zip: addr.PostalCode.substring(0, 5),
idx: idx
};
}
var addresses = processResult(JSON_FROM_SUCCESS_FUNCTION);
// now you can loop over addresses array and access each.
addresses.forEach(function(addressObject) { console.log(addressObject) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories