Not able to access nested JSON values after sending through socket - javascript

I'm writing a Node.JS code which acts as an intermediate between JavaScript client and Google DialogFlow. My problem is, when I try to echo the JSON object response to the client through a web socket connection, the nested values always read as null.
My JSON Object:
{
responseId: 'xxxx-xxxxxx-xxxxxx-xxxx',
recognitionResult: null,
queryResult: {
fulfillmentMessages: [ [Object] ],
outputContexts: [ [Object], [Object], [Object] ],
queryText: '21',
speechRecognitionConfidence: 0,
action: 'age',
parameters: { fields: [Object] },
allRequiredParamsPresent: true,
fulfillmentText: 'All right!',
webhookSource: '',
webhookPayload: null,
intent: {
inputContextNames: [],
events: [],
trainingPhrases: [],
outputContexts: [],
parameters: [],
messages: [],
defaultResponsePlatforms: [],
followupIntentInfo: [],
name: 'Intent name',
displayName: 'Default Intent',
priority: 0,
isFallback: false,
webhookState: 'WEBHOOK_STATE_UNSPECIFIED',
action: '',
resetContexts: false,
rootFollowupIntentName: '',
parentFollowupIntentName: '',
mlDisabled: false
},
intentDetectionConfidence: 1,
diagnosticInfo: null,
languageCode: 'en',
sentimentAnalysisResult: null
},
webhookStatus: { details: [], code: 0, message: '' },
outputAudio: <Buffer >,
outputAudioConfig: {
audioEncoding: 'OUTPUT_AUDIO_ENCODING_OGG_OPUS',
sampleRateHertz: 0,
synthesizeSpeechConfig: null
}
}
I'm trying to access the name value of intent. I also need to pass all the other values as well.
My Web Socket code:
const ws = require('ws');
const wss = new ws.Server({ noServer: true });
function onConnect(ws) {
ws.on('message', function (newMessage) {
ws.send(JSON.stringify(data));
}
}
(I've trimmed out parts that are irrelevant)

Related

Cheerio XML to array or object

I scrape with cheerio and node-fetch a XML data.
I would like my scraping object in JSON or array convert but how make I this?
How I can convert and access this in a array?
const $ = load(responseText, {
xmlMode: true,
});
let dataLength = ($('item').length);
console.log(dataLength);
const items = ($('item'));
My object is:
prevObject: <ref *7> LoadedCheerio {
'0': Document {
parent: null,
prev: null,
next: null,
startIndex: null,
endIndex: null,
children: [Array],
type: 'root'
},
length: 1,
options: { xml: false, decodeEntities: true, xmlMode: true },
_root: [Circular *7]
}

how to set time to xmpp stanzas object

i have a xmpp server, then i have function to send message via xmpp and i use npm (#xmpp/client) for nodejs
var message = 'test';
const stanzas = xml("message", {
to: receiver,
type: "notification",
time: time.datetime()* //not work
}, xml("body", null, message),
xml("time", "urn:xmpp:time")) // not work
await xmpp.send(stanzas).catch(console.error);
*(2022-06-02T13:39:31Z)
This function works and send correct
The problem is that i cant set timeStamp for this
I just try to send time in main object of message, send in xml - no success
my result stanzas is:
Element {
name: 'message',
parent:
Element {
name: 'stream:stream',
parent: null,
children: [],
attrs:
{ version: '1.0',
xmlns: 'jabber:client',
'xmlns:stream': 'http://etherx.jabber.org/streams',
to: 'localhost',
'xml:lang': undefined } },
children:
[ Element { name: 'body', parent: [Circular], children: [Array], attrs: {} },
Element {
name: 'time',
parent: [Circular],
children: [],
attrs: [Object] } ],
attrs:
{ to: 'testJabber',
type: 'notification',
time: '2022-06-02T13:39:31Z' } }
What i get as a function success result:
()testServer : test
What i should get:
(02.06.2022 13:39:31)testServer : test

How to get javascript variable with Cheerio

When I check request data in Postman it returns HTML file and contains JavaScript value.
<html>
<body>
HTML VALUES...
</body>
<script>
var _ITEMID = '29041549';
var ITEM_VID = '612c86e6c6f7840001d0c821';
var _SOLDOUT = '1' == 0;
var _DISCOUNTPRICE = '110.00';
var _SIZE = 'S,M,L,XL';
var _ITEMTYPE = '0';
var _COLORPICS = '';
</script>
<script>another script value</script>
<script>another script value</script>
<script>another script value</script>
<script>another script value</script>
</html>
I use got package to request data.
And I want to get script's value, but when I tried this code, it returns undefined.
I already checked this article and modify this codes but it seems it doesn't fit my case.
const got = require('got');
const cheerio = require('cheerio');
const data = await got(`https://www.vvic.com/item/${itemDetailURL}.html`);
// console.log(data);
const $ = cheerio.load(data);
const calData = $('script').get()[0];
console.log(calData); // Returns undefined
[console.log($('script'));]
LoadedCheerio {
length: 0,
options: { xml: false, decodeEntities: true },
_root: <ref *1> LoadedCheerio {
'0': Document {
type: 'root',
parent: null,
prev: null,
next: null,
startIndex: null,
endIndex: null,
children: [Array]
},
length: 1,
options: { xml: false, decodeEntities: true },
_root: [Circular *1]
},
prevObject: <ref *1> LoadedCheerio {
'0': Document {
type: 'root',
parent: null,
prev: null,
next: null,
startIndex: null,
endIndex: null,
children: [Array]
},
length: 1,
options: { xml: false, decodeEntities: true },
_root: [Circular *1]
}
}
[console.log($('script').get());]
[] // Returns empty array

Sequelize .set error, .set is not a function

I am trying to set up a belongsTo and hasMany association which seems to be working, but when I run .set I am getting the error fighterData.setUsers is not a function. The dialect is mySql. Here is my code:
Fighters.belongsTo(Users)
Users.hasMany(Fighters);
Users.sync()
Fighters.sync()
//creates the table if it doesn't exist
const insertFighter = function(obj, sessId) {
return Fighters.create(obj, {returning: true}).then((fighterData) => {
//console.log('inserted a fighter \n', fighterData);
return Users.findOne({
where: {
id: sessId
}
}).then((userData) => {
//console.log('fighterData in findOne promise \n', fighterData)
return fighterData.setUsers(userData)
}).then((success)=> {
console.log('user fighter join success')
return
}).catch((err)=> {
console.log('user fighter join error \n', err)
return
})
}).catch((err)=> {
console.log('error inserting fighter \n', err);
})
}
The error that's logging is user fighter join error.
interestingly, userData.setFighters(fighterData) works successfully, but that is not what I need
EDIT
This is what fighterData is:
fighterData in findOne promise
Fighters {
dataValues:
{ id: 7,
name: 'Gilbert Burns',
image:
'https://www.sherdog.com/image_crop/200/300/_images/fighter/20140806063215_IMG_8432.JPG',
next_opponent: 'Kamaru Usman',
next_fight: 'July 11, 2020 ',
style: 'mma',
updatedAt: 2020-06-17T06:00:40.368Z,
createdAt: 2020-06-17T06:00:40.368Z },
_previousDataValues:
{ name: 'Gilbert Burns',
image:
'https://www.sherdog.com/image_crop/200/300/_images/fighter/20140806063215_IMG_8432.JPG',
next_opponent: 'Kamaru Usman',
next_fight: 'July 11, 2020 ',
style: 'mma',
id: 7,
createdAt: 2020-06-17T06:00:40.368Z,
updatedAt: 2020-06-17T06:00:40.368Z,
UserId: undefined },
_changed:
{ name: false,
image: false,
next_opponent: false,
next_fight: false,
style: false,
id: false,
createdAt: false,
updatedAt: false,
UserId: false },
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'Fighters', singular: 'Fighter' },
omitNull: false,
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: {} },
hooks: {} },
_options:
{ isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
isNewRecord: false }
This is returned from entering one fighter's information into the database.
The problem is with the naming of your models.
Sequelize expects your models to be named in singular form (User instead of Users), so it's getting confused with what it should name the generated setter and getter methods for your association.
If you try fighterData.setUser(userData) instead of fighterData.setUsers(userData), it should work.
If you you want to use setUsers instead, you will have to make adjustments to your model to tell Sequelize to use Users as the singular form of User:
Users.init({
sessId: Sequelize.STRING
}, {
sequelize: sequelize,
name: {
singular: 'users'
}
});
You can overwrite the plural form the same way as well.
You can read more about this here: Sequelize naming strategy

Node.js - Counting the number of objects in MongoDB collection

I am new to Node.js and MongoDB and I am really struggling to wrap my head around callbacks. I have read a few articles but it is still quite confusing to me. In the code below, I am trying to return the count of orders that have some properties which I have expressed in the query in orderModel.count(query, next):
controllers/order.js:
var mongoose = require ('../config/db');
var orderModel = require('../models/order').model;
var User = require('./user');
var Error = require('../config/error');
createOrder: function (user, order, next) {
if (newOrder.totalPrice > user.credit && orderModel.
count({$and: [{user: order.user}, {active: true}, {$or: [{status: 0}, {status: 1}]}]},
function(err, count){
if(err)
console.log(err);
else
count; }) > 0)
return next({error: Error.InsufficientCredits});
}
I don't think I am correctly obtaining the variable count because when I tried printing out the result of the second condition in the if statement, I got this data printed out:
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts: { bufferCommands: true, capped: false },
name: 'orders',
collectionName: 'orders',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'dsXXXXXX.mlab.com',
port: XXXXXX,
user: 'XXXX',
pass: 'XXXX',
name: 'X',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db: [Object],
_events: {},
_eventsCount: 0 },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
....
You need to put your logic inside the Model.count() method callback function as:
var mongoose = require ('../config/db'),
orderModel = require('../models/order').model,
User = require('./user'),
Error = require('../config/error');
var createOrder = function (user, order, next) {
orderModel.count({
"user": order.user,
"active": true,
"status": { "$in": [0, 1] }
}, function(err, count) { //<-- put logic in this callback
if (err) {
console.log(err);
throw err;
} else if (newOrder.totalPrice > user.credit && count > 0) {
// logic for creating order here
} else {
return next({ "error": Error.InsufficientCredits });
}
})
}

Categories