Sending data to service array brute force - javascript

I can't find an answer to my question, can you help me friends
what kind of requests, I get: facebook, linkedin, reddit
I don't want to write a lot of code, so I want to ask you how I can make
How do I create a check loop, and send the data (the data is the same for all services)
to go through and find the right service. send the right service and data. Again, the data for all services is the same
as you can see, I write a lot of conditional statements, and I don't like it, I want to put
I use ejs, express
I just want to get rid of a lot of code..
everything into one loop and work
var servies = ["facebook", "linkedin", "reddit"]
servies.forEach(service => {
console.log(service);
});
if (service == "linkedin") {
res.render('linkedin', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
if (service == "reddit") {
res.render('reddit', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
if (service == "facebook") {
res.render('facebook', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}

You can try
var servies = ["facebook", "linkedin", "reddit"]
servies.forEach(service => {
console.log(service);
res.render(service, {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
});
since in your example code, you don't do anything different between the different services, but only replace the string name of the service, and you already have a loop for that.

Related

Bad Request in Discord.js (Node) and cant find out whats causing it

Im coding a bot in Discord.js (Node) and I'm trying to send an embed with the server info, I've got all the code but it keeps causing a Bad Request and I've tried everything I know here's the code:
var FieldsData = [{ name: "Channels", value: msg.guild.channels.size }, { name: "Emojis", value: msg.guild.emojis.size }, { name: "Members", value: msg.guild.members.size }, { name: "Owner", value: msg.guild.owner }, { name: "Roles", value: msg.guild.roles.size }, { name: "Region", value: msg.guild.region }, { name: "Id", value: msg.guild.id }, { name: "Icon", value: msg.guild.iconURL }, { name: "Created At", value: msg.guild.createdAt }];
msg.channel.send('', {
embed: {
color: 37119,
title: "Server info for " + msg.guild.name,
fields: FieldsData
}
});
I've tried the message with just one field and it works,
I've tried it will each field by themselves and it works
but when I put them all together they make a Bad Request,
I've checked every line, every character and I'm just
stumped at what could possibly be causing this,
the max fields is 25 and I don't have that many,
all the variables are valid, none produce 'Null' or 'Undefined',
I've tried different setups of the code layout,
I've tried adding/removing parts, editing parts, replacing bits
here and there but to no avail I cant get it to work at all.
I've been trying to figure this out for 2 hours, I've searched online, docs, etc
Please Note: I'm not that advanced with javascript so if i've made a big mistake then don't be surprised.
"msg" is the object of the message, Example:
Bot.on('message', function (msg) { /*Stuff*/ });
I hope I've explained this enough, I'm using the LATEST version of Discord.js at the time of posting this and I'm not using ANY other extensions, packages, etc
SHORT ANSWER:
Now, don't just ignore this post after I say this (actually read my reasons, the whole thing), but please just use a Rich Embed
LONG ANSWER:
First of all, I strongly suggest using Rich Embeds, as it is easier to play with and edit. Anyways, here:
The first suggestion comes from your message event. In ES6, we now have arrow functions which look like this (arg1, arg2) => {doSomething();}, and using this new feature, your message event handler should look more like this:
client.on('message', msg => {
//Do my thing with that msg object
});
Now back to the point.
Objects are weird k? I believe that this: "Server info for " + msg.guild.name is not allowed. I don't know why, but when I tried to use a variable to display my bot's version, it gave me an error too. So if you want to fix that you have two options:
Recommended: Use Rich Embeds
Not Recommended: Use `${myVar}` instead (Not Tested)
Don't overcomplicate. What is this: ('', You can just do msg.channel.send({embed:{}});
You don't just use variables for the sake of it. What is the point of using FieldsData? It is only used once, and why can't you just do:
msg.channel.send({
embed: {
color: 37119,
title: "Server info for " + msg.guild.name,
fields: [{name: "Channels", value: msg.guild.channels.size}, { name: "Emojis", value: msg.guild.emojis.size }, { name: "Members", value: msg.guild.members.size }, { name: "Owner", value: msg.guild.owner }, { name: "Roles", value: msg.guild.roles.size }, { name: "Region", value: msg.guild.region }, { name: "Id", value: msg.guild.id }, { name: "Icon", value: msg.guild.iconURL }, { name: "Created At", value: msg.guild.createdAt }]
}
});
VERY IMPORTANT NOTE:
Now, you don't give any valid reason why you don't want to use Rich Embeds, because a rich embed is also an object. ;-; So just use a rich embed.
i have scripts that require the use of objects, and they are pre made
I wonder how you get access to your embed if its not stored.... Very interesting.

Sequelize: .createAssociation() or .setAssociation doesn't update the original object with created data

I've been stuck on this for a while. Take the following code as an example:
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
models.RankedStats.create({
totalWins: 0,
totalLosses: 0
}).then(function(rankedStats) {
summoner.setSummonerRankedStats(rankedStats).then(function() {
console.log(summoner.SummonerRankedStats)
//This outputs undefined
summoner.getSummonerRankedStats().then(function(srs) {
console.log(srs)
//This outputs the RankedStats that were just created
})
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
console.log(summoner.SummonerRankedStats)
//This outputs the SummonerRankedStats object
})
})
})
})
So, to put it simply... If I have a Summoner (var summoner) and perform a .setAssociation() or .createAssociation() on it, and then log summoner, the data created isn't there. If I fetch it again from the database (with .getAssociation() or by searching for that Summoner again) I can access it, but I was hoping to avoid that extra DB call.
Is there a way to add this information to the original object when using .create() or .set()? It can be achieved by doing something like:
summoner.dataValues.SummonerRankedStats = rankedStats
But that seems somewhat hacky :)
Is there a correct way to do it, or does it even make any sense?
Thanks in advance!

Meteor User table value axtracting

How do I pick the email address value from meteor Mongo user table?
I have written below query to pick the element:
users=Meteor.users.find({},{emails:1})
This the code I have written to fetch the email address, but I don't know how much it's affecting performance in the code:
users = Meteor.users.find({})
users.forEach(function(key,option){
key.emails.forEach(function (key,option){
console.log(key.address)
});
});
In meteor, you should call:
users = Meteor.users.find({}, { fields: { emails: 1 } })
Reference in docs
EDIT
Please remember users is a cursor object. Cursor objects can be handled directly in templates, and must be the return of publications. You can't iterate a cursor directly in a javascript loop.
Example: (remember authorization in production publications)
Meteor.publish('user-emails', function() {
return Meteor.users.find({}, { fields: { emails: 1 } });
});
If you want to directly access the user instances, for example to iterate them in a javascript code, you need to fetch the cursor (reference in docs).
Example:
var users = Meteor.users.find({}, { fields: { emails: 1 } }).fetch();
Now users is an array of users. Feel free to iterate them.
Example (I'm using underscore.js):
var users = Meteor.users.find({}, { fields: { emails: 1 } }).fetch();
_.each(users, function(user) {
console.log(user.emails);
});
Now, if you need a vector only with emails, one on each index, you can pluck the emails from a fetched array with underscore.js (reference of pluck)
var emails = _.pluck(Meteor.users.find({}, { fields: { emails: 1 } }).fetch(), 'emails');
Hope it works :)
if its not working, dont forget to return
return users

Binding Separate Groups of JSON Data to a UserID Number AngularJS

I've been having trouble figuring out how to keep data as separate forms, but binding together inside of angularJS. This is for educational and testing purposes so I don't need to worry about setting this data to a db or using any type of storage for now other than the apps session and localstorage. For the test I will hard code into my JS.
I'm uploading a photo to showcase my thoughts and I'll explain it as well:
So my main data is a customers group. I have it set to iterate through and display using ng-repeat. No big worries there. I can add, and update each of these. When I had the proposals attached to the customers json object then when I edited the user, it would delete those proposals and quotes. So I want to keep them separate, but allow them to be called into the DOM by specific user.
My Problem:
Is that I do not know how to bind objects, to objects, and have them update in the dom anytime another action happens. Here is a pen of what I have so far
http://codepen.io/ddavisgraphics/pen/pvRZOv?editors=101.
Example of the Code Data:
var customerArray = [
// Start Customer
//--------------
{
customerID:1,
customer: 'Joe Frankelton',
phone: 1244957323,
email: 'jFrank#gmail.com',
// start address
address: {
line1:'248 Gallows Rd',
city:'Hangtown',
state:'West HangState',
zip:24750
},
}, // End Customer
// Start Customer
//--------------
{
customerID:2,
customer: 'Danny Manny',
phone: 1245423323,
email: 'dman#gmail.com',
// start address
address: {
line1:'253 Cow Run Rd',
city:'Beeftown',
state:'PA',
zip:24750
},
}, // End Customer
];
var proposals = [
{ // Proposal 1
customerID: 1,
projectTitle: 'Gameify Me Captin',
type: 'GameDesign',
deadline: 'Jan. 2, 2015',
deliveryType: 'Files',
problem: 'The problem is that the customer wants to much crap.',
notes: 'clients mother wants to be involved because she designed a peice of toast in 1973',
},
{ // Proposal 2
customerID: 2,
projectTitle: 'Playing',
type: 'Website',
deadline: 'Jan. 2, 2017',
deliveryType: 'Sites',
problem: 'Everything',
notes: 'client will be easy to work with, wants pink and blue',
},
];
var quotes = [
{
customerID: 2,
quoteNum: 2,
projectTitle: 'Project Title',
type: 'Graphic Design',
deadline: 'Jan. 2, 2015',
billableHrs: 11,
hourlyRate: 42.50,
externalCost: 33.99,
tax: 0.6,
}
];
What you can do is to create a viewmodel for customer by mapping the data from multiple sources, i.e customers, proposals and quotes.
You can use customerID to do the linking, example:
customer.proposals = proposals.filter(function(prop){
return prop.customerID === custId;
});
So you would do:
function getMappedCustomer() {
return customerArray.map(function(customer){
var custId = customer.customerID;
customer.proposals = proposals.filter(function(prop){ return prop.customerID === custId;});
customer.quotes = quotes.filter(function(quot){ return quot.customerID === custId; });
return customer;
});
}
// Init current data
$scope.customers = getMappedCustomer();
Similarly do it when you do the maping of updated customer. If you want to preserve customerArray use angular.copy(customerArray) and do the mapping on it.
Demo

Make ember to resolve hasMany relationship when loading

I'm currently facing a big problems for days. I'm using ember simple-auth plugin which provide me a session object accessible through the code or the templates. That session object store the account information such as username, id and rights.
My models are like this :
App.Right = DS.Model.extend({
label: DS.attr('string', { defaultValue: undefined })
});
App.Right.FIXTURES = [
{
id: 1,
label: 'Admin'
}, {
id: 2,
label: 'Manager'
}, {
id: 3,
label: 'User'
}
];
App.User = DS.Model.extend({
username: DS.attr('string'),
rights: DS.hasMany('right', {async: true})
});
App.User.FIXTURES = [
{
id: 1,
username: "Someone",
rights: [1]
}
];
Then I have (as specified on the simple-auth documentation) this setup :
App.initializer({
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
account: function() {
var userId = this.get('userId');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
...
}
});
Inside one of my view I'm doing this:
this.get('context.session.account.rights').toArray()
but it gives me an empty array. That piece of code is executed inside an Ember.computed property.
The question is how can I resolve the childrens of account before rendering the view ?
Since async: true this.get('context.session.account.rights') will return a promise object so you will have to use this.get('context.session.account.rights').then(... see: http://emberjs.com/api/classes/Ember.RSVP.Promise.html#method_then
Okay so I finally got it to work. It doesn't solve the original question because the original question was completely stupid. It's just IMPOSSIBLE to resolve relationships synchronously when you use the async: true. Trying to resolve it in advance is NOT the solution because you will still not know when it has actually resolved.
So here is the solution:
$.each(this.get('cellContent.buttonList'), function(i, button) {
button.set('hasAccess', false);
this.get('context.session.account').then(function(res) {
res.get('rights').then(function(result) {
button.set('hasAccess', Utils.hasAccess(result.toArray(), button.rights));
});
});
});
Using the following cellContent.buttonList definition:
buttonList: [
Ember.Object.create({
route: 'order',
label: 'Consult',
rights: 'all'
}), Ember.Object.create({
route: 'order.edit',
label: 'Edit',
rights: [1, 2]
})
]
Explanation
We have to use Ember.Object in order to have access to the set method. Using an Ember object is very handy. It allows us to change the value of properties after the render process making the view to update according to the new value you just set.
Because it updates the view, you don't have to care anymore whether your model has resolved or not.
I hope this will help people as much as it helps me.

Categories

Resources