Opening link in javascript widget in new window - meteor

I get the following error with this code in the update function below and I don't understand why.
err: [RangeError: Maximum call stack size exceeded]
Does it have something to do with using Meteor.setTimeout()?
if (Meteor.isServer) {
Meteor.clearTimeout(league.nextPickTimeoutId);
var pickTimeoutId = Meteor.setTimeout(function () {
Meteor.call('pickPlayer', leagueId, findTopScoringPlayer(leagueId, nextTeam._id)._id);
}, 30*1000);
Leagues.update(leagueId, {
$set: {
nextPickTill: new Date().getTime() + (league.secondsPerPick * 1000),
nextPickTimeoutId: pickTimeoutId
}
}, function (err) {
if (err) console.log('err:', err);
});
}

The problem was that:
Meteor.setTimeout() returns a handle that can be used by Meteor.clearTimeout. Source
The Meteor.clearTimeout() function confused me that I thought took an id as an argument.

Related

Exception in delivering result of invoking method

I've been testing on http calls with meteor, I used nitrous (because I had no access to my dev laptop during the weekend) and it worked fine.
But when I tried to run from my local pc it returns:
Exception in delivering result of invoking 'getMatch': TypeError:
Cannot read property 'duration' of undefined.
Any ideas of what could be the cause?
Method definition:
Dota = {};
Dota.getMatch = function() {
if (!Meteor.settings.steamToken)
throw new Meteor.Error(500, 'Enter a valid Steam Token in Meteor.settings');
var matchResponse = Meteor.http.get(
"https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?",
{
params:{
"match_id": "1305454585",
"key": Meteor.settings.steamToken
}
}
);
if (matchResponse.statusCode === 200) {
return matchResponse.data.result
}
else {
throw new Meteor.Error(500, "getMatch failed with error: "+matchResponse.statusCode);
}
}
Meteor.methods({
'getMatch': function(){
return Dota.getMatch();
}
})
Calling the method:
Meteor.call('getMatch', function(error, result){
var duration = numeral(result.duration).format('00:00:00');
Session.set('duration', duration);
var winner = Meteor.myFunctions.getWinner(result.radiant_win);
Session.set('winner', winner);
});
Template.layout.helpers({
winner: function () {
return Session.get('winner');
},
duration: function () {
return Session.get('duration');
}
});
Found a solution, I changed the location of
Meteor.methods({
'getMatch': function(){
return Dota.getMatch();
}
})
to server/server.js (I had it in packages/dota/dota.js) and now it works! Thanks #user3374348 for helping!

meteor iron:router Blaze.ReactiveVar calling multiple times

I have a route I call many times. I have to subscribe two collections for having all datas, here's a snapshot:
var one = new Blaze.ReactiveVar(false);
var two = new Blaze.ReactiveVar(false);
this.route('stopIndex', {
path: '/stop/:section/:stop_id',
waitOn: function() {
Meteor.call('getTripIdsForStop', {
stop_id: this.params.stop_id,
from: fromNow(),
to: toMax(),
db: prefix
}, function(err, ids) {
DEBUG && console.log('TRIP_IDS:', ids);
Meteor.subscribe(prefix + '_trips', {
trip_id: {$in: ids}
}, function() {
one.set(true);
});
Meteor.subscribe(prefix + '_stop_times', {
trip_id: {$in: ids}
}, function() {
two.set(true);
});
});
return [
function () { return one.get(); },
function () { return two.get(); }
];
},
The first time I call the route, all goes fine. The second time, the one and two vars are already setted to true so the waitOn doesn't wait and I get a no data message on my template for some seconds, until collections responds. I've tried putting on the first lines of waitOk method:
one.set(false);
two.set(false);
but this makes the waitOn to wait forever. Am I doing something wrong or missing something? Thanks for the help.
I've solved this way:
Router.onStop(function() {
one.set(false);
two.set(false);
});
that invalidates ReactiveVars and will wait. I've also moved all code from waitOn to data. Now the waitOn is like this:
return [
function () { return one.get(); },
function () { return two.get(); }
];

Meteor - insert failed: Method not found

I have a problem with my Meteor's JS file. I get this error "insert failed: Method not found" when I try to insert any data to the database and reflect on chart. I've tried fetching data directly from db that didn't work too...
thanx in advance.
LinePeople = new Mongo.Collection("LinePeople");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
if (Meteor.isClient) {
console.log("in LIne Client");
//LinePeople = new Mongo.Collection(null);
Template.linenvd3.rendered = function() {
var chart = nv.models.lineChart()
.margin({left: 80}) //Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
nv.addGraph(function() {
chart.xAxis.axisLabel('Person number').tickFormat(d3.format('d'));
chart.yAxis.axisLabel('Age (years)').tickFormat(d3.format('d'));
d3.select('#lineChart svg').datum(
[{ values: LinePeople.find().fetch(), key: 'Age' }]
).call(chart);
nv.utils.windowResize(function() { chart.update() });
return chart;
});
Deps.autorun(function () {
d3.select('#lineChart svg').datum(
[{ values: LinePeople.find().fetch(), key: 'Age' }]
).call(chart);
chart.update();
});
};
Template.linenvd3.events({
'click #addDataButton': function() {
console.log(" in line addButton");
var age = getRandomInt(13, 89);
var lastPerson = LinePeople.findOne({}, {fields:{x:1},sort:{x:-1},limit:1,reactive:false});
if (lastPerson) {
console.log(" in lastPerson.. if block");
LinePeople.insert({x:(lastPerson.x + 1), y:age});
} else {
console.log(" in lastPerson.. else block");
LinePeople.insert({x:1, y:age});
}
},
'click #removeDataButton': function() {
console.log(" in line removeButton");
var lastPerson = LinePeople.findOne({}, {fields:{x:1},sort:{x:-1},limit:1,reactive:false});
if (lastPerson) {
LinePeople.remove(lastPerson._id);
}
}
});
}
if (Meteor.isServer) {
console.log("in line Server");
}
While following the Getting Started tutorial on the official meteor.js website I've had the same problem with autopublish turned on.
Turned out the issue was I created my Tasks collection inside the imports/ folder. Thus it was not implicitly imported on the server.
I had to explicitly import it on the server to solve the issue.
server/main.js
import { Meteor } from 'meteor/meteor';
import '../imports/api/tasks.js';
Meteor.startup(() => {
// code to run on server at startup
});
As you can see the import is not used by my code but is required anyways.
Thanks for the help... I actually got it worked by publishing the collection and giving it some permissions:
This code is placed in "myapp/shared/collections.js". (Placed them separately to handle all the other collections which I would add for other graphs)
lineVar = new Meteor.Collection("linenvd3");
lineVar.allow({
insert: function () {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
This code is placed in "myapp/server/publish.js"
Meteor.publish('line', function () {
return lineVar.find();
});
Then, this is modified Javascript made look more simpler and comprehensive.
if (Meteor.isClient) {
Meteor.subscribe('line');
Template.linenvd3.rendered = function() {
var chart = nv.models.lineChart()
.margin({left: 80})
.useInteractiveGuideline(true)
.transitionDuration(350)
.showLegend(true)
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
nv.addGraph(function() {
chart.xAxis.axisLabel('Person number').tickFormat(d3.format('d'));
chart.yAxis.axisLabel('Age (years)').tickFormat(d3.format('d'));
d3.select('#lineChart svg').datum(
[{ values: lineVar.find().fetch(), key: 'Age' }]
).call(chart);
nv.utils.windowResize(function() { chart.update() });
return chart;
});
Deps.autorun(function () {
d3.select('#lineChart svg').datum(
[{ values: lineVar.find().fetch(), key: 'Age' }]).call(chart);
chart.update();
});
};
}

Meteor cfs standard packages - check Error

While trying to upload a File to my Database, I am getting a Match Error that is preventing the File to be stored.
Here is the Basic code:
The Initialization:
UserImages = new FS.Collection("userImages", {
stores: [new FS.Store.FileSystem("userImages", {path: "~/uploads"})],
filter: {
maxSize: 1048576, //in bytes
allow: {
contentTypes: ['image/*'],
extensions: ['png', 'jpg']
},
onInvalid: function (message) {
if (Meteor.isClient) {
alert(message);
} else {
console.log(message);
}
}
}
});
if(Meteor.isServer){
UserImages.allow({
insert:function(userId, doc){
return true;
},
update:function(userId, doc, fields, modifier){
check(doc, Object);
return true;
},
remove:function(){
return true;
}
})
}
The Client Code:
Template.editProfile.events({
'change #profileUpload':function(event, template){
var files = event.target.files;
for (var i = 0, ln = files.length; i < ln; i++) {
UserImages.insert(files[i], function (err, fileObj) {
if(err){
console.log(err);
}
});
}
}
});
Strangly enough, if i run a console.log(typeof file) it gives me back an Object. But when i check the File against an Object with check(file, Object) it gives me this Error:
This is the Stack from the Server:
Exception in setTimeout callback: Error: Match error: Expected plain object
at checkSubtree (packages/check/match.js:279:1)
at check (packages/check/match.js:32:1)
at UserImages.allow.update (app/server/allowances.js:91:7)
at packages/mongo/collection.js:1041:1
at Array.every (native)
at Function._.every._.all (packages/underscore/underscore.js:219:1)
at [object Object].Mongo.Collection._validatedUpdate (packages/mongo/collection.js:1038:1)
at [object Object].m.(anonymous function) (packages/mongo/collection.js:851:1)
at Object.methods.rateLimit.callFunctionsInQueue (packages/matteodem:easy-security/lib/easy-security.js:72:1)
at packages/matteodem:easy-security/lib/easy-security.js:116:1
Has anyone encountered this problem or has a solution for a workaround? I've tried all kinds of workarounds also with Match.Any but than I get an error telling me that all Arguments have not been run against the check();
I checked the issues in here:
https://github.com/CollectionFS/Meteor-cfs-base-package/issues
https://github.com/CollectionFS/Meteor-CollectionFS/issues
but could not find a solution so far.
Thanks for the help!

Unable to pass result to router after calling Meteor.methods

I encounter an error using Meteor. I call an Method.method.
Template.WelcomeTemplate.events({
'click #btn-findgame': function(e) {
e.preventDefault();
console.log('clicked find game button');
Meteor.call('allocateGame', function(error, id) {
if (error) {
alert(error.reason);
} if (id) {
Router.go('gameRoom', {_id: id})
}
})
}
})
With my Method, I check if there is an room available, create one when the isn't otherwise join. And return the ID of this room.
Meteor.methods({
allocateGame: function () {
console.log('allocateGame method called')
var user = Meteor.user();
// find game where one player is in the room
var gameWaiting = Games.findOne({players: {$size: 1}})
if (!gameWaiting) {
console.log('no game available, create a new one');
var newGameId = Games.insert({players: [user._id], active: false, finished: false});
GameDetails.insert({gameId: newGameId, gameData: []});
return newGameId
} else {
if (_.contains(gameWaiting.players, user._id)) {
console.log('Cannot play against yourself sir')
} else {
console.log('Joining game');
Games.update({_id: gameWaiting._id}, {
$set: {active: true},
$push: {players: user._id}
});
return gameWaiting._id;
}
};
}
})
And my Router:
Router.map(function () {
this.route('welcome', {
path: '/',
controller: WelcomeController})
this.route('gameRoom', {
path: '/game/_:id'
})
});
The Error I recieve is:
Exception in delivering result of invoking 'allocateGame': TypeError: Cannot read property 'charAt' of null
at Object.IronLocation.set (http://localhost:3000/packages/iron-router.js?e9fac8016598ea034d4f30de5f0d356a9a24b6c5:1293:12)
And indeed, If I don't return an ID the Routing will continue as normal. However when I return an ID in my WelcomeTemplate an error will occur.
EDIT:
Even thought my MongoDB is updating my MiniMongo DB is empty. There must be a problem with syncing. Any idea where to look?
In the route, you set the path to be '/game/_:id', that is, a parameter with the name id. In your call to Router.go, you pass a parameter with the name _id.
Don't know if this solves your problem, but it's an error.
This kind of embarrassing taking in account how many hours I've spent on fixing this. The error was created because of an error in my routers.js
this.route('gameRoom', {
path: '/game/_:id'
})
Should be:
this.route('gameRoom', {
path: '/game/:_id'
})
Happy coding.

Resources