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

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.

Related

Update a document in an array and return the document in mongoDB

So I have an only array in a collection, which has a name of "posts". I am trying to update a document in that array and return the updated document. I tried this:
Posts.updateOne(
{},
{
$set : {
'posts.$[id].image' : cloudinaryUrl,
'posts.$[id].post' : req.body.updatedPost
}
},
{
arrayFilters: [
{ 'id._id': new ObjectId(req.body.postID) },
],
},
);
I'm getting this:
{
"data": {
"acknowledged": true,
"modifiedCount": 1,
"upsertedId": null,
"upsertedCount": 0,
"matchedCount": 1
}
}
And also this:
Posts.findOneAndUpdate(
{
'posts': {
$elemMatch: {
creatorId: req.userData.userId,
_id: new ObjectId(req.body.postID),
}
}
},
{
$set : {
'posts.$.image' : cloudinaryUrl,
'posts.$.post' : req.body.updatedPost
}
},
)
And I'm getting the whole collection (I'm just showing you 1 post):
{
"data": {
"_id": "63ddd8059b4324f25f69469e",
"__v": 0,
"posts": [
{
"post": "h123jjkkl",
"image": "",
"comments": [],
"likes": 0,
"creatorId": "63cdb85f5f2fb46f75781f7e",
"date": "2023-02-04T04:36:31.982Z",
"_id": "63dde0cf749dde1d574c29cf"
},
]
But I can't get the updated document. Can someone help me do it?
const updatedData = await User.findOneAndUpdate(
{ _id: userId },
{ $set: { 'posts.$[id].image' : cloudinaryUrl,
'posts.$[id].post' : req.body.updatedPost } },
{ returnDocument: "after" }
);
You will get the updated document, you can use a async function or can get
the data using .then and avoid the await keyword

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; });

Where to put http get call inside a javascript promise

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;
});
};
}

Populating the AJAX url in a JSTree with model information

I am populating a JSTree view with ajax commands. My current JS code is as follows
$(document).ready(function() {
$("#navigation").jstree({
"json_data": {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = "";
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
nodeId = node.attr('id');
url = "#Url.Action("EventTreeItems", "Events")" +"?selectedYear=" + nodeId;
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0 }; },
"success": function() {
}
}
},
"themes": {
"theme": "classic"
},
"plugins": ["themes", "json_data", "ui"]
});
});
I would like to eliminate the if statement from the "ajax" property and fill it with the JSON data that is coming from the server. The JSON data looks like this
[{"data":{"title":"2012","attr":{"href":"/Events/EventList?selectedYear=2012"}},"attr":{"id":"2012","selected":false,"ajax":"/Events/EventTreeItems?selectedYear=2012"},"children":null,"state":"closed"},.....]
How can I feed the "ajax" property from the json into the "ajax" property in the JSTree?
For future reference I fixed it by doing the following
.jstree({
"json_data": {
"ajax": {
"url": function (node) {
var url;
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
url = node.attr('ajax');
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0, ajax: n.attr ? n.attr("ajax") : 0 }; },
"success": function() {
}
}
},

Categories