Javascript data mapping - javascript

Can someone explain to me how can I implement in a clean way a solution to get a status (string) from combining two other ones?
I need to declare a function which takes two params (two strings) and needs to return another one based on the combination of those two strings.
For ex:
carStatus(status, secondaryStatus) => string
where secondaryStatus can have multiple options.
I'm thinking using an if/else if statement which returns a third status which I need.
For ex when status is 'OPEN' and secondaryStatus is 'payment1' or 'payment2' or 'payment3', the function must return a new string (status) like 'CONFIRMED'.
So, an example of how I'm thinking to implement at this moment would be something like this:
carStatus = (status, secondaryStatus) => {
if(status === 'OPEN' && (secondaryStatus === 'payment1' || 'payment2' || 'payment3')){
return 'CONFIRMED';
} else if(status === 'CANCELLED' && (secondaryStatus === 'payment4' || 'payment5' || 'payment6')){
return 'REMOVED';
} else if(status === 'REVIEW' && (secondaryStatus === 'payment2' || 'payment5' || 'payment5')){
return 'CHECKED';
}
}
<div>carStatus('OPEN', 'payment1')</div>
In div must be rendered 'CONFIRMED'.
In my implementation, I'll have to write I think other 5 else if statements.. so maybe there is a cleaner way to implement this.
My project is written in React, but I'm thinking to put this function in utils folder. Perhaps a solution written in React could be more clean? I don't know.
Any help will be appreciated.

You can probably use a lookup object for the various options. Since criteria given is very vague following is a very basic example
const carStatus = (carState, carSecondaryState) => {
const secondaries = {
ORDERED: 'CLIENT'
}
return `${secondaries[carSecondaryState]}_${carState}`
}
console.log(carStatus('NEW', 'ORDERED'))

Related

Firestore security rule that checks field under random document in collection to allow update in other collection

I am working on a project that was created without any security and I am trying to lock things down to acceptable levels.
It's an Angular/Ionic app using AngularFire.
Issues started when locking down users writes to the user itself, because the application contains a chat function.
When a chat message is created, the application code uses a batch write to update both involved users, of which the latter obbviously fails.
The batch write code looks like:
const batch = this.db.firestore.batch();
const sellerUserDoc = this.db.firestore.collection(this.collectionId()).doc(this.toUserDocId(sellerExtendedUser));
batch.set(sellerUserDoc, this.createExtendedUserOfferConversationUpdateItem(sellerExtendedUser, offerConversation), { merge: true });
const buyerUserDoc = this.db.firestore.collection(this.collectionId()).doc(this.toUserDocId(buyerExtendedUser));
batch.set(buyerUserDoc, this.createExtendedUserOfferConversationUpdateItem(buyerExtendedUser, offerConversation), { merge: true });
return batch.commit();
My question is about how to add a security rule / modify query or other code that allows another user to be written to, if a conversation exist between them.
Currently a conversation is created in the conversations collection, with a random ID, which contains both user ids.
Then there is the users collection, which has a map of conversation, that currently does not get populated with the ID because of the rules/query.
I have spend hours watching videos, posts here, and trying thigns out without succes.
I think my main problem is that when a user update gets done, I am unable to get the conversation ID ( and I got the message that security rules are not filters :) ).
This is an example of an attempt with non working findings commented out( I am using the emulator on a dev machine):
match /users/{document=**} {
allow write: if request.auth.uid == resource.data.id || isConvPartner();
allow read,update: if request.auth.uid == resource.data.id || getConversations(request.auth.uid)
allow create: if request.auth != null;
}
function isConvPartner() {
let isBuyer = get(/databases/staging-v1-conversations/documents).data.buyerId == request.auth.uid;
let isSeller = get(/databases/staging-v1-conversations/documents/$(resource.data.id)).data.sellerId == request.auth.uid;
return isBuyer || isSeller
}
function getConversations(uid){
let conversationsForuser = get(/databases/staging-v1-conversations/documents).data.values.buyerId.hasAny(uid);
match /{prefix=**}/staging-v1-conversations/{docId} {
allow read,write,update: if request.auth.uid == resource.data.buyerId
|| request.auth.uid == resource.data.sellerId
|| request.data.id == resource.data.id
|| get(/databases/staging-v1-conversations/documents/$(docId)).data.buyerId == request.auth.uid
|| get(/databases/staging-v1-conversations/documents/$(docId)).data.sellerId == request.auth.uid
|| resource == null
|| request.auth != null;
allow create: if request.resource.data.buyerId == request.auth.uid || request.resource.data.sellerId == request.auth.uid;
function recipeData() {
return get(/databases/$(database)/documents/$(docId)).data.buyerId == request.auth.id
}
}
return conversationsForuser
}
I thought about modifying the way data is written, but I cannot really think of a way to write this data to another user then either - the rule has to allow it.
Is this the correct approach and how should the security rules look like precisely?
Some pictures from the emulator to show the database structure:
Any help is greatly appreciated, thank you!
[update]
I am trying to use the following function to allow the second user to be updated:
function getConvForUser(loggedInId,userId){
let user = loggedInId;
let userFetched = user-MYkirTsKsmCNevww40IzQpn0m6fX;//get(/databases/staging-v1-users/documents/$(user));
let conversationsList = userFetched.conversations.conversationsForuser0[0];
//get(/databases/staging-v1-conversations/documents/$(resource.data.conversations.keys()[0])).data.buyerId == request.auth.uid
let conversations = "conversation-" + conversationsList;
let conversationsForuser = get(/databases/staging-v1-conversations/documents/$(conversations)).buyerId.hasAny(userId);
let conversationsForuser2 = get(/databases/staging-v1-conversations/documents/$(conversations)).sellerId.hasAny(userId);
//let listOfConv = getAfter(/databases/staging-v1-conversations/documents).data.values.join(",");
return conversationsForuser || conversationsForuser2
}
Parameters for calling are the logged in user and the userid for the user that needs to be updated.
[/update]

Jquery The name '' is does not exists in the current context

Although there are several same questions, I'm very curious regarding this specific case.
jQuery(document).ready(function () {
if ($('#msg').val() != '' && $('#msgSuccess').val() == 'true') {
var msg = $('#msg').val();
var t = $('#msg').val().toString();
toastr.success("#_localizer[t]");
}
});
variable t has some message which represents the key for my localization file.
I have issue to pass that variable (string) to my mvc _localizer.
Where I go wrong with this?
If I add simple console.log(t) it works. So Im guessing that is the localizer is a problem.
I'm using #inject IViewLocalizer _localizer from AspNetCore.Mvc.Localization

Discord.js check for a user mention inside a message

I have this code:
const args = message.content.split(" ");
args.shift();
var mention = message.mentions.users.first()
const subject = args[0];
if (!subject) {
return message.say(`*you wand projects a stream of water*`)
} else if (subject === mention) {
return message.say(`*Your wand projects a stream of water at ${mention} and they are now soaked*`)
and I am trying to get it to pick up the mention.users.first() variable called mention so people can specify to shoot the spell at someone. I can't quite figure out how to get it to be checked. I've tried a couple of things like:
} else if (subject === mention) {
} else if (subject === 'mention') {
} else if (subject === {mention}) {
I knew this one probably wouldn't work but I tried it:
} else if (subject === ${mention}) {
I can't figure out if I'm not wording it properly or if it is just the wrong way to do entirely. Any pointers or ideas would be appreciated.
Well a role mention in <Message>.content would take the form of <#&ID>, it will be a sstring, discord.js already has a static property of the regex needed to validate role mentions which is: /<#&(\d{17,19})>/g, so now you just have to test if the string passes:
const regex = /<#&(\d{17,19})>/g;
if(regex.test(subject)) {
}
Also like I said you can get this regex by the static property
https://discord.js.org/#/docs/main/v12/class/MessageMentions?scrollTo=s-ROLES_PATTERN
const {MessageMentions} = require("discord.js");
const regex = MessageMentions.ROLES_PATTERN;

How to move javascript if conditions to external file?

Working on a script to transfer data between some software, in this script I have an if condition to ignore some particular fields that do not need to be transferred. Because of this I have a condition that looks something like:
if(
object.field == "_Field1" ||
object.field == "_Field2" ||
object.field == "_Field3" ||
object.field == "_Field4"
...
) { ... }
However there are quite a few of these fields and more will likely emerge so I would like to move these fields to an external (text, or js?) file for easier maintenance and readability, how can I accomplish this without moving the if? Ideally I would like to be able to have another script which will write to this file when it needs to add a new field so the file should be just the comparisons.
you can add the fields that you want to ignore on array and just remove them befor the actual object send:
const ignoredFields=['_Field2','_Field2','_Field3','_Field4']
// or you can read them from a file
const mustIgnore = ({field})=>
return ignoredFields.includes(field)
and now you can use mustIgnore dynamically without changing or adding if statement
You could simply create a function that did this evaluation and returned the result. Something like this:
function isObjectOneOfSpecificFieldSubsets(object) {
return (
object.field == "_Field1" ||
object.field == "_Field2" ||
object.field == "_Field3" ||
object.field == "_Field4"
)
}
Then your code above would become:
if(isObjectOneOfSpecificFieldSubsets(object)) {
...
}
I don't know if I understood your problem well but you could:
have a file that only contains the list of fields you want to check:
const FIELDS = [
"_Field1",
"_Field2",
...
]
have a file with a util:
const doFieldsCheckCondition = (field) => {
...
for (let tmp_field of FIELDS) {
...
}
}
and then use this function in your original script:
if (doFieldsCheckCondition(field)) {...}

discord.js: JSON planet property is undefined

I'm making a Discord bot using discord.js, and I'm starting to add JSON stuff to it, so that I can store info for individual users, in a separate file. However, I keep getting an error that says planet is not defined, at the line that says if (bot.log[mentionedGuyName].planet == undefined) {. There are some variables, modules etc. in here that haven't been declared or whatnot, but that's only because if I put all my code on here, it would be pages long. My JSON file is called log.json.
The general purpose of this code block, if it helps, is to see if the user already has a "planet". If so, the bot finds gets that value from the JSON file, and sends it to the channel. If not, then it picks a random one (code I didn't put here because of size)
I think I understand at least kind of why the error is occurring (the planet property isn't defined), but I'm not sure how to fix it. If anyone knows how to declare a JSON property or whatever is going on here, I and my server would be most grateful. Thanks in advance!
Here's my JavaScript file:
let mentionedGuy = message.mentions.members.first();
let mentionedGuyName = null;
let noMentions = message.mentions.members.first() == false ||
message.mentions.members.first() == undefined;
if (noMentions) return;
else mentionedGuyName = mentionedGuy.user.username;
if (message.content.startsWith(prefix + "planet")) {
if (message.content.length > 7) {
if (bot.log[mentionedGuyName].planet == undefined) {
bot.log[mentionedGuyName] = {
planet: jMoon
}
fs.writeFile('./log.json', JSON.stringify(bot.log, null, 4), err => {
if (err) throw err;
});
message.channel.send(targeting);
message.channel.send(coords);
} else {
message.channel.send(bot.log[mentionedGuyName].planet);
}
}
}
Change it so it checks the typeof
if(typeof <var> == 'undefined') //returns true if undefined
Noting that typeof returns a string
Source

Categories

Resources