Skip to content

Instantly share code, notes, and snippets.

@stephentcannon
Forked from arunoda/1.docs.md
Created August 25, 2013 19:56
Show Gist options
  • Save stephentcannon/6335925 to your computer and use it in GitHub Desktop.
Save stephentcannon/6335925 to your computer and use it in GitHub Desktop.

##Meteor Latency Compensation - The Correct Way

This is a kind of correction I wan't make regards to the concept describe in discover-meteor book

For the latency compensation to occur we cloud simply share the same method in the client/server. We can do this by simply putting the method under a place which can see by bot the server and client.

But practically(not all the time) we should not do that. In the server code we might have some logic which should not share. Or simply we might have some secret tokens.

So the correcy approach is define the method (in this case post) seperately in the two context. as shown below

In the client implementation just update the collection (and do the validations)

//located in: client/methods/posts.js
Meteor.methods({
"post": function(postData) {
postData.submitted = Date.now();
Posts.insert(postData)
}
});
//located in: server/methods/posts.js
Meteor.methods({
"post": function(postData) {
var user = Meteor.user();
if(!postData.url || !postData.title) {
throw new Meteor.Error(422, "URL and Title must exists!");
}
if(!user) {
throw new Meteor.Error(401, "Unauthorized!");
}
var existingPostWithUrl = Posts.findOne({url: postData.url});
if(existingPostWithUrl) {
throw new Meteor.Error(302, "URL already exists", existingPostWithUrl._id);
}
var post = _.extend(_.pick(postData, 'url', 'title', 'message'), {
author: user.username,
userId: user._id,
submitted: Date.now()
});
//apply some secret formula here
var Future = Npm.require('fibers/future');
var future = new Future();
//for just show the latency
Meteor.setTimeout(function() {
post.title += " - server";
future.ret();
}, 5000);
future.wait();
var postId = Posts.insert(post);
return postId;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment