Write assertion subject to whether key has value - javascript

I'm trying to come up with a method that would allow me to create a it block that confirms whether my configuration file has a specific attribute. The object has in it:
exports.config = {
services: [
['sauce', {
sauceConnect: true,
}]
],
}
I would like to have an it block that would confirm whether this value is true and if it isn't, then it should fail.
I have tried a couple approaches like if (sauceConnect in services) etc but it isn't an approach that is working. The test and the configuration file are in separated documents and for the life of me I can't work out a good enough test.
I'd appreciate any help or answers here.

On the assumption that this is how you want your config to look like, you'll have to loop through it and find the match:
const exportedConfig = {
services: [
['sauce', {
sauceConnect: true,
}],
['key', {
data: "value",
}]
],
}
// [1] refers to the 2nd element in the array, aka the value
// some looks for ANY match and if a match occurs it returns true.
console.log(exportedConfig.services.some(element => element[1].sauceConnect == true ))
Though, a recommendation would be to format your config as so:
const exportedConfig = {
services: {
sauce: {
sauceConnect: true,
},
key: {
data: "value",
}
},
}
``

Related

Accessing Hierarchy Data in an Object Javascript

I need to access the id value in a Javascript object to display a simple message that the user has membership if the id value equals a specific value.
I'm getting Uncaught Type Error not defined 'id' message
In the console it's displayed as
subscriptions: Array(1)
0: // COMMENT Don't know what this is
autoRenew: false
canRenew: false
expiryDate: "2022-10-26T00:00:00"
membership:
id: "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL"
I'm assuming equivalent JSON is something like:
subscriptions {
0
{
membership: {
id: "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL"
}
}
}
My Javascript Code
const userObj3 = userObj['subscriptions']['0']['membership']['id'];
if (userObj3 = "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL") {
greeting = "You have membership";
}
Your subscriptions are an array, also your comparison inside the if is incorrect and should be == or ===, you could also use dot annotation to traverse the object instead of using brackets on every key.
Using the index as a string instead of a number isn't really wrong, it's just not a good practice.
You might want to think about looping through the subscriptions instead of using the direct index just in case there's multiple subscriptions. But that just depends on how you structure your data and is kinda up to you.
const userObj = {
subscriptions: [
{
autoRenew: false,
canRenew: false,
expiryDate: '2022-10-26T00:00:00',
membership: {
id: '819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL'
}
},
{
autoRenew: true,
canRenew: false,
expiryDate: '2022-10-26T00:00:00',
membership: {
id: '201AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL'
}
}
]
};
let greeting = "You're not a member";
userObj.subscriptions.forEach((sub) => {
if (sub.membership.id === '201AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL') {
greeting = "You're a member";
}
});
console.log(greeting);

How to find failed facts from json rule engine

I am new to the rules engine and I am trying to create a rules engine in javascript.
I have the following rule and Passing one parameter as the wrong input, how to find which argument (fact) is mismatched (not the rule).
engine.addRule({
conditions: {
all: [{
fact: 'score',
operator: 'greaterThanInclusive',
value: 200
}, {
fact: 'players',
operator: 'equal',
value: 10
}]
},
event: {
type: 'success',
}
})
let fact = {
score: 150,
players: 10
}
It will fail the rule. How do I know which fact cause the failure of rule?
We gives a property event which will fired when rules match . If rules match the length of events going to be greater than 0.
Example:
const { events } = await engine.run(facts);
if (events.length > 0) {
return true
}
In the case of failure of rule events length going to be zero.

Sequelize counting associated entries with separate

I'm trying to count the associated entries using the separate attribute in my includes to improve performance (without it the request it's taking 5s). But I'm receiving the following error:
"message": "missing FROM-clause entry for table "likedPosts""
Sorry for bad english, it's not my first. I hope you understand and can help me.
My code:
#Query((returns) => [Post], {
nullable: true
})
async getAllFeedPostsByUserId(#Arg('user_id') user_id: number): Promise < Post[] > {
const result = await Post.findAll({
attributes: {
include: [
[Sequelize.fn("COUNT", Sequelize.col("likedPosts.feed_post")), "likesAmount"]
]
},
include: [{
model: LikedPosts,
as: 'likedPosts',
attributes: [],
separate: true,
}, ]
});
return result;
}
I think group is must to count entries.
Post.findAll({
attributes: {
include: [[Sequelize.fn('COUNT', Sequelize.col('likedPosts.feed_post')), 'likesAmount']]
},
include: [{
model: LikedPosts,
attributes: []
}],
group: ['likedPosts.feed_post'] // groupBy is necessary else it will generate only 1 record with all rows count
})
I can see seperate
separate desc
To elaborate: by default, to retrieve the related model instance, Sequelize will use a SQL JOIN. By enabling separate, Sequelize will perform a separate query for each of the associated models, and join the resulting documents in code (instead of letting the database perform the join).

How to check if object prop exists while of destructuring?

I have this statement :
const {
'xsi:Event': {
'xsi:eventData': [
{
'xsi:call': [
{
'xsi:extTrackingId': [extTrackingId],
'xsi:personality': [personality],
'xsi:internalReleaseCause': [releaseCause],
},
],
},
],
},
} = data
I'm parsing complicate object from some api. On top is real example of object. In some cases, i have same structure, but without property 'xsi:internalReleaseCause', so in this case i cant define a value for releaseCause constant.
Question is how to check if 'xsi:internalReleaseCause' prop exists, on the fly?
const data= {
'Event': {
'eventData': [
{
'call': [
{
'extTrackingId': [],
'personality': [],
'internalReleaseCause': ['hi'],
},
],
},
],
},
}
var { Event: {eventData: [{call:[{extTrackingId:[],personality:[],internalReleaseCause}]}]} } = data;
console.log(internalReleaseCause[0])
we can use this object destruction to identify internalReleaseCause on the fly but you have some special characters (:) in object keys. I am not sure how to escape them but if there is a way you can get rid of them, then the below snippet works and you can identify the object directly. Hope this helps!

Conditionally Update/Insert and Add To Array

I have .tsv file with some orders information. After remake into my script i got this.
[{"order":"5974842dfb458819244adbf7","name":"Сергей Климов","email":"wordkontent#gmail.com"},
{"order":"5974842dfb458819244adbf8","name":"Сушков А.В.","email":"mail#wwwcenter.ru"},
{"order":"5974842dfb458819244adbf9","name":"Виталий","email":"wawe2012#mail.ru"},
...
and so on
I have a scheema into mongoose.
var ClientSchema = mongoose.Schema({
name:{
type: String
},
email:{
type: String,
unique : true,
required: true,
index: true
},
forums:{
type: String
},
other:{
type: String
},
status:{
type: Number,
default: 3
},
subscribed:{
type: Boolean,
default: true
},
clienturl:{
type: String
},
orders:{
type: [String]
}
});
clienturl is an password 8 chars length, that generated by function.
module.exports.arrayClientSave = function(clientsArray,callback){
let newClientsArray = clientsArray
.map(function(x) {
var randomstring = Math.random().toString(36).slice(-8);
x.clienturl = randomstring;
return x;
});
console.log(newClientsArray);
Client.update( ??? , callback );
}
But i dont undestand how to make an update. Just if email already exsists push orders array, but not rewrite all other fields. But if email not exsists - save new user with clienturl and so on. Thanks!
Probably the best way to handle this is via .bulkWrite() which is a MongoDB method for sending "multiple operations" in a "single" request with a "single" response. This counters the need to control async functions in issue and response for each "looped" item.
module.exports.arrayClientSave = function(clientsArray,callback){
let newClientsArray = clientsArray
.map(x => {
var randomstring = Math.random().toString(36).slice(-8);
x.clienturl = randomstring;
return x;
});
console.log(newClientsArray);
let ops = newClientsArray.map( x => (
{ "updateOne": {
"filter": { "email": x.email },
"update": {
"$addToSet": { "orders": x.order },
"$setOnInsert": {
"name": x.name,
"clientUrl": x.clienturl
}
},
"upsert": true
}}
));
Client.bulkWrite(ops,callback);
};
The main idea there being that you use the "upsert" functionality of MongoDB to drive the "creation or update" functionality. Where the $addToSet only appends the "orders" property information to the array where not already present, and the $setOnInsert actually only takes effect when the action is actually an "upsert" and not applied when the action matches an existing document.
Also by applying this within .bulkWrite() this becomes a "single async call" when talking to a MongoDB server that supports it, and that being any version greater than or equal to MongoDB 2.6.
However the main point of the specific .bulkWrite() API, is that the API itself will "detect" if the server connected to actually supports "Bulk" operations. When it does not, this "downgrades" to individual "async" calls instead of one batch. But this is controlled by the "driver", and it will still interact with your code as if it were actually one request and response.
This means all the difficulty of dealing with the "async loop" is actually handled in the driver software itself. Being either negated by the supported method, or "emulated" in a way that makes it simple for your code to just use.

Categories

Resources